text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Array begin from 0 or 1 in Delphi 5.0 Pascal?
I want to do an ArrayList in Delphi 5.0. So I found a solution doing this code:
var arr: array of String;
OK, but every time I add something I do this:
var
Form1: TForm1;
var arr : array of String;
procedure TForm1.Button1Click(Sender: TObject);
var aux :string;
var len:integer;
begin
len := Length(arr) + 1;
SetLength(arr, len);
arr[len-1] := 'abc' + IntToStr(len);
Button1.Caption := arr[len-1]; // just to writeout something
end;
I'm a C++ programmer, and I do not know anything about Pascal. I always heard a Pascal index begins from 1, not 0. As in the above procedure I do arr[len-1] because of 0 index begin.
Is there a better way than Pascal arrays? Like with C++'s std::vector?
A:
Dynamic arrays' indexes begin with zero
var
a: array of Integer;
begin
SetLength(a, 500);
a[0] := 0;
Static arrays can have arbitrary indexes
var
i: Integer;
b: array [50..100] of Integer;
c: array[-10..10] of Integer;
begin
for i := 50 to 100 do b[i] := i * i;
// Note negative starting index above in declaration
for i := -10 to 10 do c[i] := i * i;
Strings' indexes begin with one
var
c: String;
begin
c := 'Zap!';
c[1] := 'W';
ShowMessage(c); /// shows 'Wap!'
Anyway you can always use Low() and High() functions which return the lower and higher index of an array.
For handling a list of strings the most commonly used class is TStringList which is found in unit Classes.
A:
What you're using is known as a dynamic array which is different from a Pascal classic array. Dynamic arrays are variable in size and the index is 0 based.
Classic Pascal arrays are not 0 nor 1 based... It's up to the programmer where the index start or ends. The only compiler restriction is that the index must be an ordinal type. You can declare
procedure x;
var
IntArr: array[50..75] of Integer;
StrArr: array[0..49] of string;
DblArr: array[1..10] of Double;
A:
Delphi Pascal also has a nice feature that helps iterating through an array of any dimension:
Simply use for i:= Low(Array) to High(Array) do....
which is completely transparent to starting offset i.e. 0,1 or 5 or whatever.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does the regular expression ^^^ mean?
I am trying to understand the following Basic Regular Expression pattern:
^^^
This is how I interpret it as:
The first caret character is treated as the anchor for marking the beginning of line.
The second and third caret characters are matched literally (as they are neither inside a character class to cause negation, and nor the first character to be treated as anchor).
So, as I understand, I expect it to match the occurrences of ^^ pattern at the beginning of a line. Do I understand it right?
However, it appears that the aforementioned regular expression matches every line in the file irrespective of its contents. This behaviour is observed when searching a text file in Sublime Text with Regex search mode enabled.
What am I missing? How do I correctly interpret the regular expression?
Update: I observe a different behavior when running the following command using bash shell:
grep "^^^" foo
where foo is the same text file as above. The regular expression matches all the lines containing the pattern ^^ towards the beginning of line.
I am now confused as to why the result differs in two cases, and how do I understand the behavior fully?
A:
What ^ matches will depend on the regular expression engine being used. In many languages (including PHP, Python, Javascript, and Java), ^ anywhere outside a character class will always match the start of the string. It will also match the start of a line when the multiline flag is enabled. Notepad++'s regular expressions use Boost, which has the same behavior (except that there's no multiline flag in NP++; ^ will always match the start of a line).
So, here, in NP++, ^^^ means: "Match the position at the start of a line. Then match the position at the start of a line. Then match the position at the start of a line.". Thus, the start of every line gets matched.
In contrast, Bash and a few others which implement BRE flavor of regular expressions treat ^ as an anchor only in certain circumstances:
A circumflex ( '^' ) shall be an anchor when used as the first character of an entire BRE. The implementation may treat the circumflex as an anchor when used as the first character of a subexpression. The circumflex shall anchor the expression (or optionally subexpression) to the beginning of a string; only sequences starting at the first character of a string shall be matched by the BRE. For example, the BRE "^ab" matches "ab" in the string "abcdef", but fails to match in the string "cdefab". The BRE "(^ab)" may match the former string. A portable BRE shall escape a leading circumflex in a subexpression to match a literal circumflex.
In this case, the first ^ is interpreted as matching the beginning of the line, and the next two ^s, since they are not the first character of the pattern, are interpreted as matching literal ^s, rather than as start-of-line anchors.
Different regular expression flavors can have very different behavior, even given the same pattern. This is one of those cases.
| {
"pile_set_name": "StackExchange"
} |
Q:
Penetration testing or Malware analysis?
My M.Sc research is about developing IDS for IOT.
I'm confused about which field should learn more about; penetration testing or malware analysis.
I have some knowledge about each one but for IDS, which is working with malware, I don't know which field I should focus on!
I'll use AI (Deep Learning) for building an IDS based on Contiki and cooja platform.
A:
IDS is not about either penetration testing or malware analysis. An IDS inspects traffic (typically) to look for Indicators of Compromise (IoC).
An IDS, then, is a consumer of whatever the IoCs are, and developing the IoCs is a function of malware and malicious traffic analysis.
So, to develop IoCs, you might want or need to know quite a lot of about both penetration testing (can help with malicious traffic analysis) and malware analysis.
What it sounds like is that you want to develop IoCs for IOT, and then deploy those IoCs in some kind of analysis platform (what you are calling an IDS).
If you want to inspect traffic for previously unknown IoCs and determine IoCs on the fly without any previously defined IoCs, then that's a completely different prospect. I have done this, but you need quite extensive experience in a number of areas. Choosing one over another will restrict what you can detect.
| {
"pile_set_name": "StackExchange"
} |
Q:
「一生懸命」と「一所懸命」の使い方は同じでしょうか?
「一生懸命」と「一所懸命」 の使い方は同じでしょうか?意味も同じでしょうか?
A:
Both 一所懸命 and 一生懸命 are currently in parallel use to mean endeavoring with all one’s might. The former literally means to risk one’s life “at a place” for achieving something, while the latter means to do something at “a risk of one’s life” for achieving something.
Though 一所懸命 and 一生懸命 are used in the same meaning, 一生懸命 was derived from 一所懸命, which originally meant that 武士 – Samurai – in ancient times survived by desperately defending their fief given or assigned by the Mikado or Shogun against invaders.
Both words are used interchangeably today because they sound almost the same and the concept of risking life on defending one's territory is no longer relevant to the people of today.
| {
"pile_set_name": "StackExchange"
} |
Q:
Arithmetic problems with java longs
I have two equations: x * x - D * y * y = 1 and x = sqrt(1 + D * y * y).
Both are algebraic manipulations of the other.
Given D, I need to solve for the smallest integer value of x so that y is also an integer. I loop through possible y values, plug them into the second equation and test if x is an integer. If it is, I return x.
The problem I have is when x, y, and D are plugged into the 1st equation, it does not equal 1.
These are some problematic values:
1. x=335159612 y=42912791 D=61
2. x=372326272 y=35662389 D=109
My intuition is that java's Math.sqrt method does not calculate such a small decimal, however BigDecimal does not have a square root method.
Is my math just wrong? If not, what can I do to accurately calculate x and y?
Edit: Here is the root of the problem along with the method that tests if a double is a a natural number.
public static void main(String[] args){
long x = 335159612, D = 61, y = 42912791;
System.out.println(Math.sqrt(D * y * y + 2)); // 3.35159612E8
System.out.println(x * x - D * y * y); // 3
}
public static boolean isNatural(double d){
return d == (int)d;
}
A:
Be careful with precisions in 'double'.
As per IEEE 754-1985 the double precision provides 16 digits (15,9 to be absolutely precise).
E.g.
a) SQRT(112331965515990542) is
335159611.99999999701634694576505237017910
Which, when converted into double, gives 3.3515961199999999E8
b) SQRT(112331965515990543)
335159611.99999999850817347288252618840968
Which, when converted into double, gives 3.3515961199999999E8.
So, as per IEEE 754-1985 definition, those values are equal.
Apparently, any further logical/mathematical checks will be, generally speaking, inaccurate.
To overcome this limitation I recommend BigMath package from www.javasoft.ch
import ch.javasoft.math.BigMath;
import java.math.BigDecimal;
class Tester {
public static void main(String[] args) {
long D = 61L, y = 42912791L;
double a = Math.sqrt(D * y * y + 1);
double b = Math.sqrt(D * y * y + 2);
System.out.println(a);
System.out.println(b);
System.out.println(a == b);
BigDecimal bda = BigMath.sqrt(new BigDecimal(D * y * y + 1), 32);
BigDecimal bdb = BigMath.sqrt(new BigDecimal(D * y * y + 2), 32);
System.out.println(bda.toString());
System.out.println(bdb.toString());
System.out.println(bda.equals(bdb));
}
}
Result:
3.35159612E8
3.35159612E8
true
335159611.99999999701634694576505237017910
335159611.99999999850817347288252618840968
false
P.s. to completely ruin your faith in standard Java maths try this:
System.out.println(0.9200000000000002);
System.out.println(0.9200000000000001);
You will see:
0.9200000000000002
0.9200000000000002
| {
"pile_set_name": "StackExchange"
} |
Q:
Import installed package pyCharm
I have pyCharm and Python 3.7. When I go to project interpreter > packages and try to download tensorflow, it outputs an error that tells me to do the command pip install tensorflow. I did that. Now, how do I import to pyCharm? This is the error, but I already did pip update
A:
Tensorflow is not availble for 3.7 version as of now.
Downgrade the python version to 3.6.4
| {
"pile_set_name": "StackExchange"
} |
Q:
Can we put blog notifications on the Community Bulletin Board instead of the header?
I want to request a change to the title bar design site wide.
I don't particularly like when blog replaces the chat in the main line up to the left of the search field. It makes it hard to leave a comment anywhere like "I'd love to move this conversation to chat - use the link at the top of every page" and then have the OP read that on the day when blog is there.
I love the new community bulletin board area where we can feature meta posts, events and blog entries better than before with the red circle and blog taking the place of chat in the title bar.
Could you revisit this design decision now that we have a very nice tool for announcements?
If you feel keeping blog instead of chat in the title bar, would you at least put a link to the main chat room as the first entry in the bulletin board at the same time as chat is missing from the title?
A:
This is an excellent idea - the changing header links are quite annoying.
With the bulletin board now available everywhere, Emmett was able to make this happen.
| {
"pile_set_name": "StackExchange"
} |
Q:
Receive android push notification in Java for Testing
Is it possible to create a client written in Java only, which registers just like an android phone client to receive push notifications?
My goal is: I want to create an integration test on my server which tests if a GCM push notification is really being send. I can not mock the sender of the push notification as that is in another part of the system, developed by other people. Mockito will not help me out here alas.
Rob.
A:
You can't use Android APIs in standard Jave as a lot of required libraries are missing.
Although you could write a AndroidTestCase which registers at the server and waits for a notification to arrive. You just need to wait for x seconds. If the notification did not arrive in the timeout or the registration failes, the test case failed.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to integrate google+ in a flex mobile application
Anybody know how can integrate google+ in a flex mobile application. While i tried to authenticate with google+ getting an error like text="Error #2032: Stream Error. URL: https://accounts.google.com/o/oauth2/auth?response%5Ftype=code&redirect%5Furi=urn%3Aietf%3Awg%3Aoauth%3A2%2E0%3Aoob&client%5Fid ..." errorID=2032]. URL: https://accounts.google.com/o/oauth2/auth.
A:
It's your lucky day, because I know how to do it :-)
The doc is Using OAuth 2.0 for Installed Applications and you get the access token from the web page title.
Below is my View and a screenshot of my app and the Google+ API console:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
viewActivate="openSWV(event)"
viewDeactivate="closeSWV(event)"
title="Getting data...">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import flash.media.StageWebView;
private static const APP_ID:String = 'XXXXXXXXX.apps.googleusercontent.com';
private static const APP_SECRET:String = 'XXXXXXXXXXXXXXXXXXX';
private static const APP_URL:String = 'urn:ietf:wg:oauth:2.0:oob';
private static const AUTH_URL:String = 'https://accounts.google.com/o/oauth2/auth?';
private var _swv:StageWebView = new StageWebView();
private function openSWV(event:ViewNavigatorEvent):void {
_swv.addEventListener(Event.COMPLETE, extractAccessToken);
_swv.addEventListener(LocationChangeEvent.LOCATION_CHANGE, extractAccessToken);
_swv.addEventListener(IOErrorEvent.IO_ERROR, closeSWV);
_swv.addEventListener(ErrorEvent.ERROR, closeSWV);
stage.addEventListener(Event.RESIZE, resizeSWV);
_swv.stage = stage;
resizeSWV();
var reqVars:URLVariables = new URLVariables();
reqVars.client_id = APP_ID;
reqVars.response_type = 'code';
reqVars.redirect_uri = APP_URL;
reqVars.state = getTimer();
reqVars.scope = 'https://www.googleapis.com/auth/userinfo.profile';
_swv.loadURL(AUTH_URL + reqVars);
}
private function closeSWV(event:Event=null):void {
stage.removeEventListener(Event.RESIZE, resizeSWV);
if (! _swv)
return;
_swv.removeEventListener(Event.COMPLETE, extractAccessToken);
_swv.removeEventListener(LocationChangeEvent.LOCATION_CHANGE, extractAccessToken);
_swv.removeEventListener(IOErrorEvent.IO_ERROR, closeSWV);
_swv.removeEventListener(ErrorEvent.ERROR, closeSWV);
_swv.dispose();
_swv = null;
}
private function resizeSWV(event:Event=null):void {
if (! _swv)
return;
// align to the right-bottom corner
_swv.viewPort = new Rectangle(stage.stageWidth - width, stage.stageHeight - height, width, height);
}
private function extractAccessToken(event:Event):void {
trace('title: ' + _swv.title);
trace('location: ' + _swv.location);
var code:String = getValue('code=', _swv.title);
if (code) {
trace('code=' + code);
closeSWV();
var reqVars:URLVariables = new URLVariables();
reqVars.code = code;
reqVars.grant_type = 'authorization_code';
reqVars.client_id = APP_ID;
reqVars.client_secret = APP_SECRET;
reqVars.redirect_uri = APP_URL;
var req:URLRequest = new URLRequest('https://accounts.google.com/o/oauth2/token');
req.method = URLRequestMethod.POST;
req.data = reqVars;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, handleComplete);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleError);
loader.addEventListener(IOErrorEvent.IO_ERROR, handleError);
loader.load(req);
}
}
private function handleError(event:ErrorEvent):void {
var loader:URLLoader = URLLoader(event.target);
trace(event.text);
trace(loader.data);
}
private function handleComplete(event:Event):void {
var obj:Object;
var loader:URLLoader = URLLoader(event.target);
trace(loader.data);
try {
obj = JSON.decode(loader.data);
} catch(e:Error) {
trace('Invalid JSON: ' + loader.data);
return;
}
trace('access_token=' + obj.access_token);
var req:URLRequest = new URLRequest('https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + obj.access_token);
var loader2:URLLoader = new URLLoader();
loader2.addEventListener(Event.COMPLETE, handleComplete2);
loader2.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleError);
loader2.addEventListener(IOErrorEvent.IO_ERROR, handleError);
loader2.load(req);
}
private function handleComplete2(event:Event):void {
var obj:Object;
var loader:URLLoader = URLLoader(event.target);
trace(loader.data);
try {
obj = JSON.decode(loader.data);
} catch(e:Error) {
trace('Invalid JSON: ' + loader.data);
return;
}
var info:Object = {
ID: obj.id,
FIRST: obj.given_name,
LAST: obj.family_name,
FEMALE: (obj.gender != 'male'),
AVATAR: obj.picture
};
_userid.text = 'id: ' + info['ID'];
_first.text = 'first: ' + info['FIRST'];
_last.text = 'last: ' + info['LAST'];
_female.text = 'female: ' + info['FEMALE'];
_avatar.text = 'avatar: ' + info['AVATAR'];
_img.source = info['AVATAR'];
title = 'Your data';
_busy.visible = false;
_busy.includeInLayout = false;
_group.visible = true;
}
private function getValue(key:String, str:String):String {
const pattern:RegExp = /[-_a-zA-Z0-9\/.]+/;
var index:int = str.indexOf(key);
if (index > -1) {
var matches:Array = str.substring(index + key.length).match(pattern);
if (matches.length > 0)
return matches[0];
}
return null;
}
]]>
</fx:Script>
<s:BusyIndicator id="_busy"/>
<s:VGroup id="_group" visible="false">
<s:Button id="_play" label="Start game"/>
<s:Label id="_token"/>
<s:Label id="_userid"/>
<s:Label id="_first"/>
<s:Label id="_last"/>
<s:Label id="_female"/>
<s:Label id="_avatar"/>
<s:Image id="_img"/>
</s:VGroup>
</s:View>
| {
"pile_set_name": "StackExchange"
} |
Q:
multiple objects for a single index in an NSArray
Is it possible to store multiple objects for a single index in an NSArray?
A:
Sure there are many ways to do this with the most common being to assign a dictionary to each array element
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there option to have powerful URL and Aliases in Drupal, not the poor one that I've found?
First of all I want to state that I've just started with Drupal so I'm a noob.
I'll try to explain what I think is a powerful URL and Alias system.
Lets say we have some structured content with some subcontent shared between main sections.
The main sections could be Visitor, Customer and Website. Now every main section has it's own menu with subsections. Let's say Visitor has Basic informations, Products. Customer has Products, Reports and Website has Basic information and Contacts. So logically the URL for content should look like this:
1.0 example.com/visitor
1.1 example.com/visitor/basic_informations
1.2 example.com/visitor/products
2.0 example.com/customer
2.1 example.com/customer/products
2.2 example.com/customer/reports
3.0 example.com/website
3.1 example.com/website/basic_informations
3.2 example.com/website/contacts
The content Products in Visitor and Customer, Basic information in Visitor and Website is the same. So it's shared (aliased) between these main sections.
And my question is how to do it Drupal are there any modules or configuration that results in this structure?
What have I found and think that doesn't do the job!
Module Pathauto: Yes it creates alias that is nicer than the ugly node/xx name, but it doesn't care about the parent section so everything look like this:
example.com/visitor
example.com/basic_informations
example.com/products
example.com/customer
example.com/reports
example.com/website
example.com/contacts
A:
You can configure pathauto to include sections in various ways. If you go to the alias settings in pathauto (www.example.com/admin/build/path/pathauto), you can set the paths there.
Expand Node path settings and then expand the replacement patterns option below it. If you have a menu with customer, visitor and website as the main links you can enter in a patten like [menu-path-raw]/[title-raw] - this will put the section in first.
Alternatively, if that menu structure doesn't work you could use taxonomy - set up a taxonomy with those three main options and add sub-categories to them as needed. Then in path-auto enter in [term-raw]/title-raw] - this again will give you the url structure you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is the Army Camp showing more troops then I have?
I am new to Clash of Clans. My problem is when I try to create new troops it stops producing because my camp is full. But my camp capacity is 65, and I have created only 33 troops. One thing to mention: this amount is decreasing when I come back from an attack. Can anyone tell me where the problem is?
A:
According to the wiki, Giants use 5 housing space each. You have 8 Giants which use 40 housing space plus 25 troops that use 1 housing space each.
8*5 + (5 + 11 + 9) * 1 = 40 + 25 = 65
| {
"pile_set_name": "StackExchange"
} |
Q:
New Google Calendar broke my script with HTML?
My script gets calendar events for a range of dates and puts them in a Google Sheet. Then I can "print" the sheet to a PDF and send to the club members.
Club members need to book in to events by email. I tried to put "mailto" links in the calendar, but they were not clickable in the PDF, so I stopped doing that, and listed the email addresses as plain text.
Now with the new Google Calendar, all email addresses put into Description fields appear as hypertext links. ("Inspect Element" shows things like
<a href="mailto:person@domain" target="_blank">person@domain</a> )
Some of these come through into the spreadsheet as hypertext links (a href="mailto: and so on), some just as the bare email addresses.
My script gets the calendar entries with
var events = cal.getEvents
(new Date(StartMonth + firstDay + ", " + StartYear + " 00:00:00"),
new Date( EndMonth + lastDay + ", " + EndYear + " 23:59:59"));
and I get the Description out of the "events" array with
events[i].getDescription()
Do you know if a recent change to the type of the Description field of Google Calendar entries could be causing the problem?
Are there options to getDescription that could convert HTML to plain text?
Or, better still, is there a way to make clickable links in the PDF produced from the Google Sheet?
Thanks, Jim
A:
Do you know if a recent change to the type of the Description field of Google Calendar entries could be causing the problem?
This is due to the update to Google Calendar, initially released Oct. 2017, but which has been rolling out over the past couple months. Google added a text formatting feature (lists, bold, italics, links) to the event description field of the updated version. They are now pushing html tags through their calendar feeds. The update is causing all sorts of problems.
Are there options to getDescription that could convert HTML to plain text?
Yes, but destructively. For the bare minimum, you could look into removing the html tags in javascript. You will lose paragraphs and line breaks this way. Another option is to use a library that can remove tags while preserving some of the plain-text/whitespace formatting, such as textversionjs
| {
"pile_set_name": "StackExchange"
} |
Q:
Как добавить в поле текст по нажатию кнопки?
<form action = "" method = "post">
<input type="submit" onclick="document.getElementById('text').value+='с';
return false;" value = "с" />
<input type = "text" name = "text" id="text" value = "" />
</form>
При нажатии на кнопку с в поле будет писаться буква с. Мне необходимо чтобы при нажатии на кнопку вставлялся html-код:
<option value="NAME">NAME</option>
Пробовал просто вставить в value+='с'; вместо буквы с этот самый код, но ничего не работает, вообще всё слетает.
A:
Попробуй вот так:
Код с одинарными кавычками:
<input type="submit" onclick="document.getElementById('text').value +='<option value=\'NAME\'>NAME</option>'; return false;" value = "с" />
Результат:
Код с двойными кавычками:
<input type="submit" onclick='document.getElementById("text").value +="<option value=\"NAME\">NAME</option>"; return false;' value = 'с'/>
Результат:
| {
"pile_set_name": "StackExchange"
} |
Q:
Vectorizing logic to check if index matches
I have the following function that works perfectly, but I would like to apply vectorization to it...
for i = 1:size(centroids,1)
centroids(i, :) = mean(X(idx == i, :));
end
It checks if idx matches the current index and if it does, it calculates the mean value for all the X values that correspond to that index.
This is my attempt at vectorization, my solution does not work and I know why...
centroids = mean(X(idx == [1:size(centroids,1)], :));
The following idx == [1:size(centroids,1)] breaks the code. I have no idea how to check if idx equals to either of the numbers from 1 to size(centroids,1).
tl:dr
Get rid of the for loop through vectorization
A:
One option is to use arrayfun;
nIdx = size(centroids,1);
centroids = arrayfun(@(ii) mean(X(idx==ii,:)),1:nIdx, 'UniformOutput', false);
centroids = vertcat(centroids{:})
Since the output of a single function call is not necessarily a scalar, the UniformOutput option has to be set to false. Thus, arrayfun returns a cell array and you need to vertcat it to get the desired double array.
A:
you can split the matrix into cells and take the mean from each cell using cellfun (which applies a loop in its inner operation):
generate data:
dim = 10;
N = 400;
nc = 20;
idx = randi(nc,[N 1]);
X = rand(N,dim);
centroids = zeros(nc,dim);
mean using loop (the question's method)
for i = 1:size(centroids,1)
centroids(i, :) = mean(X(idx == i, :));
end
vectorizing:
% split X into cells by idx
A = accumarray(idx, (1:N)', [nc,1], @(i) {X(i,:)});
% mean of each cell
C = cell2mat(cellfun(@(x) mean(x,1),A,'UniformOutput',0));
maximum absolute error between the methods:
max(abs(C(:) - centroids(:))) % about 1e-16
| {
"pile_set_name": "StackExchange"
} |
Q:
Detener la ejecución al lanzar un Activity
Yo programaba en C#, en Windows, pero ahora estoy desarrollando en Android:
Quiero lanzar un Activity, ya conozco cómo lanzarlo con INTENTS, StartCativity(typeof(ActivityALanzar)), y StartActityForResult(), pero la ejecución continúa, es decir que al lanzar el Activity, se lanza en otro hilo.
Yo quiero algo como como lo existe en los formularios .Net (form.ShowDialog()), que el Activity se lance en el mismo hilo y que el Activity padre se quede esperando que el Activity hijo cierre.
Ya intenté deteniendo el hilo principal pero esto colapsa la App.
¿Cómo puedo resolver esto?
A:
Lo que buscas es un DialogFragment que se muestra encima de tu activity y no que se abra otra vista.
Para esto tienes que crear una clase que herede de DialogFragment. Por ejemplo:
public class MiFormularioDialogo extends DialogFragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View layout = inflater.inflate(R.layout.layout_de_tu_activity, container, false);
// buscamos los elementos de la vista para asignar asignarles eventos a estos
Button button = (Button)layout.findViewById(R.id.show);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// evento click del button
}
});
return layout; // retornamos la vista
}
}
En la parte donde esta inflater.inflate(R.layout.layout_de_tu_activity, container, false); tienes que reemplazar layout_de_tu_activity por el nombre del layout de la actividad que quieres que se muestre. Utiliza la variable layout para asignar los eventos a las vistas del dialogo.
Entonces para mostrarlo utilizas el getFragmentManager():
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.addToBackStack(null);
// Inicializamos el dialogo y lo mostramos
DialogFragment newFragment = new MiFormularioDialogo()
newFragment.show(ft, "dialog");
| {
"pile_set_name": "StackExchange"
} |
Q:
How to echo a MSSQL datetime field $row into PHP
I'm trying to create a simple table displaying data from June 2019, however i'm having trouble getting the MSSQL datetime row to eacho out properly. Initially it broke my code and was blank, then i tried using the date() strtotime php function, which now just shows 31 01 1970 for all columns which is incorrect.
Here's a example of the input 2016-07-04 00:00:00.000
Below is my code.
<?php
$serverName = "SQL,1433";
$connectionInfo = array( "Database"=>"", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
$sql = "SELECT TOP 1 * FROM [all sales data]";
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
?>
<tr>
<td><?php echo $row['Order Point Account'];?></td>
<td><?php echo $row['Analysis Category'];?></td>
<td><?php echo $row['Branch Code'];?></td>
<td><?php echo date("d m Y", strtotime($row->date));?></td>
<td><?php echo $row['Product Discount Group'];?></td>
<td><?php echo $row['End Product Cost of Sale'];?></td>
<td><?php echo $row['End Product Other Value'];?></td>
<td><?php echo $row['End Product Sales Value'];?></td>
<td><?php echo $row['End Product Analysis Quantity'];?></td>
<td><?php echo $row['Invoice Account'];?></td>
<td><?php echo $row['Magic Number'];?></td>
<td><?php echo $row['Order Number'];?></td>
<td><?php echo $row['PAC Level 1'];?></td>
<td><?php echo $row['PAC Level 2'];?></td>
<td><?php echo $row['PAC Level 3'];?></td>
<td><?php echo $row['PAC Level 4'];?></td>
<td><?php echo $row['Product Code'];?></td>
<td><?php echo $row['Salesman 1'];?></td>
<td><?php echo $row['Statement Account'];?></td>
<td><?php echo $row['Supplier Account'];?></td>
<td><?php echo $row['Contact']?></td>
<td><?php echo $row['Order Source'];?></td>
<td><?php echo $row['User'];?></td>
<td><?php echo $row['Customer Order No'];?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
below is the vardump
object(DateTime)#1 (3) { ["date"]=> string(26) "2016-07-04 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/London" }
Here's the result of print_r($row);
Array ( [Order Point Account] => [Analysis Category] => AD [Branch Code] => 100 [Transaction Date] => DateTime Object ( [date] => 2016-07-04 00:00:00.000000 [timezone_type] => 3 [timezone] => Europe/London ) [Product Discount Group] => [End Product Cost of Sale] => 165.19999694824 [End Product Other Value] => 165.2 [End Product Sales Value] => 369.60000610352 [End Product Analysis Quantity] => 1 [Invoice Account] => [Magic Number] => 800713 [Sales Order Line Number] => [Order Number] => 319651 [PAC Level 1] => d [PAC Level 2] => dLB [PAC Level 3] => dLB01 [PAC Level 4] => dLB0106 [Product Code] => [Salesman 1] => 9500 [Statement Account] => [Supplier Account] => [Contact] => fax [Order Source] => FAX [User] => [Customer Order No] => )
Any ideas what i'm doing wrong to get this data to display correctly?
Many thanks!
A:
There are 4 issues in your code:
Issue 1:
You have typo here $row,[Transaction Date].
Issue 2:
Your column name is date not Transaction Date
Issue 3:
Your response in object form not in array format.
Issue 4:
You are using t in date format, which return Number of days in the given month
<td><?php echo date("t m Y", strtotime($row,['Transaction Date']));?></td>
Should be:
<td><?php echo date("d m Y", strtotime($row->date));?></td>
PHP Manual
| {
"pile_set_name": "StackExchange"
} |
Q:
BK3001BA Keyboard not connecting after entering correct passcode
I can't seem to connect my BA3001BA Bluetooth keyboard to my mac. It pairs, and then asks for a passcode. I enter the passcode and I get the spinning beachball of death and shortly thereafter, it says the pairing wasn't successful. I managed to connect the device to an Ubuntu Laptop by bypassing the passcode, but it's not possible on a mac.
A:
So in my experimenting I stumbled upon the Bluetooth file transfer app. I was desperate it seems so I tried sending a file to my keyboard. It ended up connecting and entering the passcode worked this time. No clue why, but it worked somehow.
I couldn't find anything like this via google, although a few people seemed to have the same problem, so leaving it here.
Thanks
| {
"pile_set_name": "StackExchange"
} |
Q:
why won't this richfaces demo project work in myeclipse web project with maven support
I'm new to Java and have been working through some tutorials to familiarize myself with some of the frameworks and technologies like JSF, Spring, and RichFaces. I'm using MyEclipse as my IDE and found a pretty good article on RichFaces+JSF2 at http://www.ibm.com/developerworks/java/library/j-richfaces4/index.html. The rest of this question is centered around the RichFaces+JSF2 demo project shown in the link above.
Now, when I create a new web project in MyEclipse using either the J2EE spec level 5.0 or 6.0 and import the demo project files, I can get the demo project deployed to myeclipse tomcat and it works fine when I visit localhost:8080/[project-name]/index.jsf.
But, if I create a new web project (either spec level) and also add maven support (either standard or MyEclipse-style), and import the same demo project files in a similar fashion, for the life of me I can't get the web app up and running. I'm using the same localhost URL as above (and referencing the new project). Deployment error output is listed below.
What am I missing?
Jul 15, 2013 1:13:31 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Users\[username]\AppData\Local\MyEclipse\Common\binary\com.sun.java.jdk.win32.x86_1.6.0.013\bin;C:\Users\[username]\AppData\Local\MyEclipse\Common\plugins\com.genuitec.eclipse.easie.tomcat.myeclipse_9.0.0.me201211011550\tomcat\bin
Jul 15, 2013 1:13:31 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Jul 15, 2013 1:13:31 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 333 ms
Jul 15, 2013 1:13:31 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Jul 15, 2013 1:13:31 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.13
Jul 15, 2013 1:13:32 PM com.sun.faces.config.ConfigureListener contextInitialized
INFO: Initializing Mojarra 2.1.3 (FCS 20110908) for context '/rf4jee6stdmvn'
Jul 15, 2013 1:13:51 PM com.sun.faces.config.ConfigureListener contextInitialized
SEVERE: Critical error during deployment:
java.lang.NoSuchMethodError: com.google.common.base.Platform.precomputeCharMatcher(Lcom/google/common/base/CharMatcher;)Lcom/google/common/base/CharMatcher;
at com.google.common.base.CharMatcher.precomputed(CharMatcher.java:664)
at com.google.common.base.CharMatcher.<clinit>(CharMatcher.java:71)
at com.google.common.base.Splitter.on(Splitter.java:127)
at org.richfaces.resource.ResourceLibraryFactoryImpl.<clinit>(ResourceLibraryFactoryImpl.java:43)
at org.richfaces.application.DefaultModule.configure(DefaultModule.java:32)
at org.richfaces.application.ServicesFactoryImpl.init(ServicesFactoryImpl.java:27)
at org.richfaces.application.InitializationListener.createFactory(InitializationListener.java:139)
at org.richfaces.application.InitializationListener.onStart(InitializationListener.java:112)
at org.richfaces.application.InitializationListener.processEvent(InitializationListener.java:157)
at javax.faces.event.SystemEvent.processListener(SystemEvent.java:106)
at com.sun.faces.application.ApplicationImpl.processListeners(ApplicationImpl.java:2139)
at com.sun.faces.application.ApplicationImpl.invokeListenersFor(ApplicationImpl.java:2115)
at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:300)
at com.sun.faces.config.ConfigManager.publishPostConfigEvent(ConfigManager.java:600)
at com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:369)
at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:225)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4334)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920)
at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Jul 15, 2013 1:13:51 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class com.sun.faces.config.ConfigureListener
java.lang.RuntimeException: java.lang.NoSuchMethodError: com.google.common.base.Platform.precomputeCharMatcher(Lcom/google/common/base/CharMatcher;)Lcom/google/common/base/CharMatcher;
at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:292)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4334)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920)
at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.NoSuchMethodError: com.google.common.base.Platform.precomputeCharMatcher(Lcom/google/common/base/CharMatcher;)Lcom/google/common/base/CharMatcher;
at com.google.common.base.CharMatcher.precomputed(CharMatcher.java:664)
at com.google.common.base.CharMatcher.<clinit>(CharMatcher.java:71)
at com.google.common.base.Splitter.on(Splitter.java:127)
at org.richfaces.resource.ResourceLibraryFactoryImpl.<clinit>(ResourceLibraryFactoryImpl.java:43)
at org.richfaces.application.DefaultModule.configure(DefaultModule.java:32)
at org.richfaces.application.ServicesFactoryImpl.init(ServicesFactoryImpl.java:27)
at org.richfaces.application.InitializationListener.createFactory(InitializationListener.java:139)
at org.richfaces.application.InitializationListener.onStart(InitializationListener.java:112)
at org.richfaces.application.InitializationListener.processEvent(InitializationListener.java:157)
at javax.faces.event.SystemEvent.processListener(SystemEvent.java:106)
at com.sun.faces.application.ApplicationImpl.processListeners(ApplicationImpl.java:2139)
at com.sun.faces.application.ApplicationImpl.invokeListenersFor(ApplicationImpl.java:2115)
at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:300)
at com.sun.faces.config.ConfigManager.publishPostConfigEvent(ConfigManager.java:600)
at com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:369)
at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:225)
... 24 more
Jul 15, 2013 1:13:51 PM org.apache.catalina.core.StandardContext start
SEVERE: Error listenerStart
Jul 15, 2013 1:13:51 PM org.apache.catalina.core.StandardContext start
SEVERE: Context [/rf4jee6stdmvn] startup failed due to previous errors
Jul 15, 2013 1:13:51 PM com.sun.faces.lifecycle.ELResolverInitPhaseListener populateFacesELResolverForJsp
INFO: JSF1027: [null] The ELResolvers for JSF were not registered with the JSP container.
Jul 15, 2013 1:13:51 PM com.sun.faces.config.ConfigureListener contextDestroyed
SEVERE: Unexpected exception when attempting to tear down the Mojarra runtime
java.lang.NullPointerException
at org.richfaces.application.CacheProvider.release(CacheProvider.java:96)
at org.richfaces.application.ServicesFactoryImpl.release(ServicesFactoryImpl.java:18)
at org.richfaces.application.ServiceTracker.release(ServiceTracker.java:132)
at org.richfaces.application.InitializationListener.onStop(InitializationListener.java:147)
at org.richfaces.application.InitializationListener.processEvent(InitializationListener.java:159)
at javax.faces.event.SystemEvent.processListener(SystemEvent.java:106)
at com.sun.faces.application.ApplicationImpl.processListeners(ApplicationImpl.java:2139)
at com.sun.faces.application.ApplicationImpl.invokeListenersFor(ApplicationImpl.java:2115)
at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:300)
at com.sun.faces.config.ConfigureListener.contextDestroyed(ConfigureListener.java:332)
at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:3866)
at org.apache.catalina.core.StandardContext.stop(StandardContext.java:4500)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4364)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920)
at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Jul 15, 2013 1:13:52 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Jul 15, 2013 1:13:52 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Jul 15, 2013 1:13:52 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/15 config=null
Jul 15, 2013 1:13:52 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 20428 ms
UPDATE
thanks to the answer below, as well as this one, i figured out what was going on.
one of the maven dependencies of the myeclipse web projects with maven support was causing the issue. so i created an exclusion for that specific jar.
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-osgi-bundle</artifactId>
<version>1.0.1-SP3</version>
<exclusions>
<exclusion>
<artifactId>google-collections</artifactId>
<groupId>com.google.collections</groupId>
</exclusion>
</exclusions>
</dependency>
the reason this works is because the richfaces demo project already includes guava, which according to the comment below this answer, is actually a newer version of google-collections.
also, sometimes after making changes to the project dependencies, a simple reload/refresh of the web app was not enough to push out the changes. i had to stop the server, remove the web app, restart the server, and re-deploy the application. perhaps that is standard practice for Java or MyEclipse or the specific changes that I was making, but I was not expecting to have to do that.
what a pain! but it has been a learning experience.
A:
That's a dependency conflict for some google's library, probably guava or google collection. To fix it, you need to have a look into your dependency tree. As you're using myeclipse, open your pom.xml file and in the tabs below select the dependency hierarchy view. Then search for the dependencies I told you. There can be different problems:
You're excluding a dependency for an artifact which needs it.
Maven is resolving a conflict with new Google's dependency, but this method is in the old one and a third-party library you are using makes use of it. In this case you should try to update your third party library or downgrade the version of the one you're using by your own.
For some artifact, you included a version of the API dependency and other version of the implementation. In this case, the execution expects to find this method but it's not available in the implementation.
Take a look to this related question.
| {
"pile_set_name": "StackExchange"
} |
Q:
java.lang.LinkageError: Failed to link freemarker/core/TemplateElement
My problem is that i have an ejb which internally uses freemarker tool to generate a HTML page, built and deployed to JBoss EAP 6.4.10. When i try to access this functionality (which generates HTML code using freemarker tool), jboss throwing below errors:
java.lang.LinkageError: Failed to link freemarker/core/TemplateElement
Caused by: java.lang.NoClassDefFoundError: javax/swing/tree/TreeNode
I added freemarker jar in my jboss modules and it's module.xml looks like this:
<module xmlns="urn:jboss:module:1.1" name="org.freemarker">
<resources>
<resource-root path="freemarker-2.3.25.jar"/>
</resources>
<dependencies>
</dependencies>
</module>
A:
Finally it is found out that the error is due to missing dependency 'javax.api' in freemaker's module.xml file, after adding this dependency in module.xml as below the problem has resolved.
<module xmlns="urn:jboss:module:1.1" name="org.freemarker">
<resources>
<resource-root path="freemarker-2.3.25.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
</dependencies>
| {
"pile_set_name": "StackExchange"
} |
Q:
Saving internet icon then re-opening causes EOF with image4j
I'm currently working on a project where I'm attempting to download a .ico file, but for some strange reason, I can't seem to open it programmatically once downloaded. I can however, open the image saved using any image editor or viewer. My code:
public static BufferedImage parseImageLocal(String url) throws IOException {
if (url.endsWith(".ico")) {
return ICODecoder.read(new File(url)).get(0);
} else if (url.endsWith(".bmp")) {
return BMPDecoder.read(new File(url));
} else {
return ImageIO.read(new File(url));
}
}
public static void saveImage(BufferedImage img, String path)
throws IOException {
File outputfile = new File(path.replace("http://", ""));
File parent = outputfile.getParentFile();
parent.mkdir();
if (!outputfile.exists()) {
outputfile.createNewFile();
}
if (path.endsWith(".ico")) {
ICOEncoder.write(img, outputfile);
} else if (path.endsWith(".bmp")) {
BMPEncoder.write(img, outputfile);
} else {
ImageIO.write(img, "png", outputfile);
}
}
And this is how i download images from the internet:
public static BufferedImage parseImage(String url) throws IOException {
URL dest = new URL(url);
if (url.endsWith(".ico")) {
return ICODecoder.read(dest.openStream()).get(0);
} else if (url.endsWith(".bmp")) {
return BMPDecoder.read(dest.openStream());
} else {
return ImageIO.read(dest);
}
}
The error is on this line:
return ICODecoder.read(new File(url)).get(0);
A:
It "seems" that you are trying to download the icon from the internet, but you are trying to treat the URL as a File.
Basically, this isn't going to be possible, File won't be able to resolve to an actual physical file.
Instead, you should be using ICODecoder#read(InputStream) and URL#openStream
Something more like...
BufferedImage img = null;
InputStream is = null;
try {
// url begin an instance of java.net.URL
is = url.openStream();
img = ICODecoder.read(is);
} finally {
try {
is.close();
} catch (Exception exp) {
}
}
return img;
Updated with example
A web resource is not a File, you can not access it as if they were, instead, you need to use the classes designed for interacting with the internet/network.
For example...
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import net.sf.image4j.codec.ico.ICODecoder;
public class ReadFavicon {
public static void main(String[] args) {
new ReadFavicon();
}
public ReadFavicon() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
try {
BufferedImage img = readIcon(new URL("https://secure.gravatar.com/favicon.ico"));
JOptionPane.showMessageDialog(null, "My FAVICON", "Icon", JOptionPane.PLAIN_MESSAGE, new ImageIcon(img));
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public BufferedImage readIcon(URL url) throws IOException {
BufferedImage img = null;
InputStream is = null;
try {
// url begin an instance of java.net.URL
is = url.openStream();
List<BufferedImage> imgs = ICODecoder.read(is);
img = imgs != null ? imgs.size() > 0 ? imgs.get(0) : null : null;
} finally {
try {
is.close();
} catch (Exception exp) {
}
}
return img;
}
}
Update with some more ideas
Now. I could be wrong, but when I ran your code, I ran into a serious of problems with the paths...
Let's assume the original url/path is https://secure.gravatar.com/favicon.ico, when you save the image, you do something like...
File outputfile = new File(path.replace("http://", ""));
File parent = outputfile.getParentFile();
parent.mkdir();
With our original path, this would result in a outputfile of https://secure.gravatar.com/favicon.ico, which is obviously wrong...
We can correct for this by using path.replace("https://", "") as well...
path = path.replace("http://", "");
path = path.replace("https://", "");
File outputfile = new File(path);
File parent = outputfile.getParentFile();
parent.mkdir();
Now, this results in a outputfile of secure.gravatar.com/favicon.ico. I become a little unstuck, as I'm not sure if this is what you want...but it does work for me...
Now, when you read the file, you do something like this...
public static BufferedImage parseImage(String url) throws IOException {
URL dest = new URL(url);
if (url.endsWith(".ico")) {
return ICODecoder.read(dest.openStream()).get(0);
} else if (url.endsWith(".bmp")) {
return BMPDecoder.read(dest.openStream());
} else {
return ImageIO.read(dest);
}
}
Now, with no evidence to the contray, I have to assume the url has not changed and is still https://secure.gravatar.com/favicon.ico...this means that new File("https://secure.gravatar.com/favicon.ico") will produce an invalid file reference
So, again, I parsed the input...
url = url.replace("https://", "");
url = url.replace("http://", "");
File outputfile = new File(url);
String parentPath = outputfile.getParent();
String name = outputfile.getName();
url = parentPath + File.separator + name;
Which produces secure.gravatar.com\favicon.ico
This all downloaded, wrote and read without error.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to determine staging or production __dev__ in app
I have same app distribute with different config - staging or production, both is running on user physical phones.
I am wishing to use __DEV__ to determine if the app is running in development or production.
But __DEV__ only work on emulator or simulator, what about app staging app on user device?
A:
Well, to access the current environment from your react-native application you are able to use the process.env.NODE_ENV variable that has production value after build.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding two decimal places
I have a column in a dataset as shown below
Col1
----------
249
250.8
251.3
250.33
648
1249Y4
X569X3
4459120
2502420
What I am trying to do is add two decimal places only to number that have only three digits , in other words, numbers that are in hundreds. For example, 249 should be converted to 249.00, 251.3 should be converted to 251.30 so on and not 4459120 or 2502420 or X569X3. The final output should look like this.
Col1
----------
249.00
250.80
251.30
250.33
648.00
1249Y4
X569X3
4459120
2502420
I have looked at many different functions so far none of those work because there are some strings in between the numbers, for example X569X3 and seven digit numbers 2502420
Actual dataset
structure(c(5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L,
16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L,
29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L,
42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L,
55L, 56L, 57L, 58L, 59L, 84L, 86L, 87L, 88L, 99L, 100L, 101L,
102L, 103L, 104L, 105L, 106L, 107L, 108L, 110L, 5L, 12L, 14L,
16L, 20L, 24L, 36L, 40L, 44L, 48L, 52L, 56L, 83L, 85L, 75L, 112L,
66L, 68L, 96L, 93L, 77L, 80L, 81L, 70L, 95L, 78L, 109L, 94L,
63L, 67L, 98L, 73L, 79L, 76L, 90L, 111L, 69L, 97L, 64L, 92L,
89L, 82L, 62L, 74L, 60L, 65L, 71L, 91L, 61L, 72L, 4L, 1L, 2L,
3L, 113L), .Label = c("1234X1", "123871", "1249Y4", "146724",
"249", "249.01", "249.1", "249.11", "249.2", "249.21", "249.3",
"249.4", "249.41", "249.5", "249.51", "249.6", "249.61", "249.7",
"249.71", "249.8", "249.81", "249.9", "249.91", "250", "250.01",
"250.02", "250.03", "250.1", "250.11", "250.12", "250.13", "250.22",
"250.23", "250.32", "250.33", "250.4", "250.41", "250.42", "250.43",
"250.5", "250.51", "250.52", "250.53", "250.6", "250.61", "250.62",
"250.63", "250.7", "250.71", "250.72", "250.73", "250.8", "250.81",
"250.82", "250.83", "250.9", "250.91", "250.92", "250.93", "2502110",
"2502111", "2502112", "2502113", "2502114", "2502115", "2502210",
"2502310", "2502410", "2502420", "2502510", "2502610", "2502611",
"2502612", "2502613", "2502614", "2502615", "2506110", "2506120",
"2506130", "2506140", "2506150", "2506160", "251.3", "251.8",
"253.5", "258.1", "275.01", "277.39", "3640140", "3670110", "3670150",
"3748210", "3774410", "3774420", "4459120", "5379670", "5379671",
"6221340", "648", "648.01", "648.02", "648.03", "648.04", "648.8",
"648.81", "648.82", "648.83", "648.84", "7079180", "775.1", "7821120",
"7862120", "X569X3"), class = "factor")
A:
Let's call your vector x:
numbers = !is.na(as.numeric(x))
x.num = x[numbers]
x[numbers] = ifelse(as.numeric(x.num) < 1000,
sprintf("%.2f", as.numeric(x.num)),
x.num)
x
# [1] "249.00" "250.80" "251.30" "250.33" "648.00"
# [6] "1249Y4" "X569X3" "4459120" "2502420"
A:
Use formatC with a selection of only the values you wish to replace.
x <- c("249", "250.8", "251.3", "250.33", "648", "1249Y4", "X569X3", "4459120", "2502420")
sel <- which(as.numeric(x) < 1000)
replace(x, sel, formatC(as.numeric(x[sel]), digits=2, format="f"))
#[1] "249.00" "250.80" "251.30" "250.33" "648.00" "1249Y4" "X569X3"
#[8] "4459120" "2502420"
A:
First, change your dataset to character:
x <- as.character(x)
Then perform the following:
ifelse(grepl("[[:alpha:]]", x) == FALSE & as.numeric(x) < 1000,
sprintf("%.2f", as.numeric(x)), x)
Or if your data is in Col1 in a dataframe:
df %>%
mutate(Col1 = ifelse(grepl("[[:alpha:]]", Col1) == FALSE & as.numeric(as.character(Col1)) < 1000,
sprintf("%.2f", as.numeric(as.character(Col1))), as.character(Col1)))
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I test my spamfilter under real world conditions?
We are currently planning to migrate our outsourced mail solution to our own servers. The last thing we need to test is the spam filter. We are going to use a cloud based spam and anti virus filter provided by Microsoft.
We now have a test server with an assigned test domain. We now want to test the spam filter under real world conditions. We thought about adding some test addresses to "no spam" lists to verify if the cloud based service is doing what it should. Is this a good idea or are there better solutions beside using our real mail server for validation of that service?
A:
A good way to test your spam-filter is by actually spamming it yourself. Try to spam it yourself by using the techniques spammers use, on smaller scale. If your protection works on small scale, you can also assume it works on bigger scale.
There are also various of tools which allow reliable testing:
SpamAssasin - GTUBE
EmailSecurityCheck
Litmus
Especially GTUBE (Generic Test for Unsolicited Bulk Email) is often used and works similar like EICAR for testing Anti-Virus setups.
However, lot of those filters also work with blacklisting. So the best testing-method is throwing your service online and see if you receive real-world spam.
| {
"pile_set_name": "StackExchange"
} |
Q:
Service Fabric - How to deploy multiple branches of code on one cluster?
Due to the hardware requirements that each cluster must have a minimum of 3 servers I'd like to use that hardware to support multiple branches/environments. Specifically we generally have 3 Dev and 3 Test branches running simultaneously for an application to support multiple parallel development project. After we release to production the code gets merged back into the other braches.
I understand I can create multiple instances of an Application Type, but what I think I really need is to have multiple versions of an Application Type on the same cluster. Its very possible that development could be happening in the A and B branches at the same time. We would want to test and deploy both branches to the Dev Cluster.
Similarly I would like to use the same cluster to expose a test environment endpoint. So as the code gets promoted I could deploy a TestB version of the application, if bug fixes happen those would be fixed and deployed in the DevB Version of that Application Type.
To handle the WebAPI endpoints Port issues we are planning on having the build script chose the environment specific WEBAPI Service manifest because it contains the port number that exposes the Service Fabric application to calling applications. So i'll have a ServiceManifest-DevB.xml file that gets renamed as plain old ServiceManifest.xml and packaged up with the DevB build when it goes out. Then ServiceManifest-TestB.xml will do the same but have a different port. Another option here is Tokenizer.
But I'm struggling on how can I have different versions of the same Application Type running on the cluster? Can I override Application Type in the parameter files or something along those lines? I am really hoping I don't need to build 6 clusters for this? That's a ton of hardware which won't fly.
Please help and thanks in advance,
Greg
A:
I had this question a year ago and had put this down. Now its back so this time I will document it!!!
I am using one cluster for both my Dev and Test environments and we use two branches for these. I needed to be able to deploy the application for these two branches under different application names.
To figure this out I followed the ps1 trail. First you look at Deploy-FabricApplication.ps1 which just passed the PublishProfile to Publish-NewServiceFabricApplication.ps1. This guy uses a method in the Utilities.ps1 called Get-ApplicationNameFromApplicationParameterFile. All this does is open the environment specific application parameter file and read it off the top:
Use this is my Dev Application Paramter file:
<Application xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="fabric:/MyAppDEVA" xmlns="http://schemas.microsoft.com/2011/01/fabric">
Use this in my Test Application Paramter file"
<Application xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="fabric:/MyAppTEST" xmlns="http://schemas.microsoft.com/2011/01/fabric">
Easy breezy when you know, and knowing is half the battle.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can path integrals be used to understand entanglement?
I like path integrals. I prefer to try to understand quantum phenomena in terms of path integrals rather than Hamiltonian mechanics. However, most of the standard texts on quantum mechanics start from Hamiltonian mechanics and mention the path integrals as a side note. This makes it difficult for me to gain insight into common phenomena (with a few exceptions like certain areas of optics) from the perspective of path integrals formulations. I am aware of some exceptions to this rule (books on path integrals in particular), but I have only seen entanglement explained from the perspective of eigenstates of a Hamiltonian.
I was wondering how entanglement would be interpreted if you started from a path integral formulation. I would be more than happy to hear from a quantum field theoretic perspective as well, but the usual quantum mechanical path integral would certainly satisfy my curiosity.
A:
Path integrals have been used to discuss entanglement of quantum fields. The path integral is used to trace out part of the system, so that the entanglement is given in terms of Von Neumann entropy, in terms of the trace of the partial density matrix.
You can find an example here for instance:
http://arxiv.org/abs/hep-th/9401125
| {
"pile_set_name": "StackExchange"
} |
Q:
Which is the best way to keep session alive?
We use keep me logged in or Remember me option to be logged in to application so to do that which is best way to achieve this feature?
Whether we have to keep cookie in browser for these or what?
Which is the best way to achieve this in application
A:
This will depend on how is the session handled on the server side. If it uses sliding expiration you could include some javascript on each page which will send a dummy AJAX request to the server at regular intervals to keep the session alive. If you want to keep the session even if the browser is closed then you need to use persistent cookies which are stored on the user computer rather than HTTP only cookies.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to read/assign the elements of a pointer that points to an array of structures in C++
In iOS core audio there is the API AudioFileWritePackets that has a inPacketDescriptions parameter defined as
'A pointer to an array of packet descriptions for the audio data.'
and it looks like this in the method signature:
const AudioStreamPacketDescription *inPacketDescriptions,
now the struct AudioStreamPacketDescription is defined as follows:
struct AudioStreamPacketDescription
{
SInt64 mStartOffset;
UInt32 mVariableFramesInPacket;
UInt32 mDataByteSize;
};
typedef struct AudioStreamPacketDescription AudioStreamPacketDescription;
I would like to know how to create and populate such a 'pointer to an array of structs', or even once given the variable, how to read it. Using the speakHere example from apple I put a breakpoint where I receive the variable and tried to dump all its contents to the log.. this is an example of an attempt:
void AQRecorder::printPacketDescriptionContents(const AudioStreamPacketDescription * inPacketDescriptions, UInt32 inNumberPackets)
{
for (int i = 0; i < inNumberPackets; ++i)
{
NSLog(@"\n----------------\n");
NSLog(@"this is packetDescriptionArray[%d].mStartOffset: %lld", i, (*inPacketDescriptions).mStartOffset);
NSLog(@"this is packetDescriptionArray[%d].mVariableFramesInPacket: %lu", i, (*inPacketDescriptions).mVariableFramesInPacket);
NSLog(@"this is packetDescriptionArray[%d].mDataByteSize: %lu", i, (*inPacketDescriptions).mDataByteSize);
NSLog(@"\n----------------\n");
}
}
any ideas?
Update: here is a sample log of me trying to mess around with it.. maybe it can help in the answer (notice at the bottom it keeps on appearing null.. it doesn't make sense that the whole thing is just a pack of zeroes since it's a variable returned by a callback that should be properly populated, also notice that it informs me about the number of packets I got back..).. also if i run the code with ((const AudioStreamPacketDescription *)(inPacketDescriptions +i))->mDataByteSize) i get a EXC_BAD_ACCESS error
(lldb) po **(inPacketDescriptions)
error: indirection requires pointer operand ('const AudioStreamPacketDescription' invalid)
error: 1 errors parsing expression
(lldb) po *(inPacketDescriptions)
(AudioStreamPacketDescription) $1 = [no Objective-C description available]
(lldb) po *(inPacketDescriptions).mStartOffset
error: member reference type 'const AudioStreamPacketDescription *' is a pointer; maybe you meant to use '->'?
error: indirection requires pointer operand ('SInt64' (aka 'long long') invalid)
error: 2 errors parsing expression
(lldb) po (*inPacketDescriptions).mStartOffset
(SInt64) $2 = 0 <nil>
(lldb) po (const AudioStreamPacketDescription *)(inPacketDescriptions +1)
(const class AudioStreamPacketDescription *) $3 = 0x00000010 [no Objective-C description available]
(lldb) po (const AudioStreamPacketDescription *)(inPacketDescriptions +1)->mStartOffset
error: Execution was interrupted, reason: Attempted to dereference an invalid pointer..
The process has been returned to the state before execution.
(lldb) po ((const AudioStreamPacketDescription *)(inPacketDescriptions +1))->mStartOffset
(SInt64) $5 = 0 <nil>
(lldb) po ((const AudioStreamPacketDescription *)(inPacketDescriptions +1))->mDataByteSize
(UInt32) $6 = 0 <nil>
(lldb) po ((const AudioStreamPacketDescription *)(inPacketDescriptions +100))->mDataByteSize
(UInt32) $7 = 0 <nil>
(lldb) po ((const AudioStreamPacketDescription *)(inPacketDescriptions +500))->mDataByteSize
(UInt32) $8 = 0 <nil>
(lldb) po inPacketDescriptions[0].mStartOffset
error: parent failed to evaluate: parent is NULL
(lldb)
also here is what it looks like in the XCode inspector:
A:
I can't remember an instance where this specific struct is ever populated by you, the client. You will need to create storage for these structs which you then pass across multiple calls in order to successfully deal with reading and writing audio data. Several non-PCM formats will need this information, depending on how the audio data has been stored.
I would like to know how to create and populate such a 'pointer to an array of structs', or even once given the variable, how to read it.
Well, there are a handful of APIs in AudioFile I/O and AudioConvertor interfaces which use this structure. Basically, you don't populate this type yourself. The basic flow goes like this:
// this is not for PCM audio data
//
// we'll read up to 8 packets at a time:
const size_t MaxPacketsToRead(8);
// allocate MaxPacketsToRead ASPDs on the stack:
AudioStreamPacketDescription aspds[MaxPacketsToRead];
// audio file read function:
AudioFileID inAudioFile = ...;
Boolean inUseCache = ...;
UInt32 outNumBytes = ...;
AudioStreamPacketDescription* outPacketDescriptions(aspds);
SInt64 inStartingPacket = ...;
UInt32 ioNumPackets = MaxPacketsToRead; // << you may not get all the packets
// you request, but this sets the
// upper limit.
void* outBuffer = ...;
OSStatus result(AudioFileReadPackets(inAudioFile,
inUseCache,
&outNumBytes,
outPacketDescriptions,
inStartingPacket,
&ioNumPackets,
outBuffer
));
if (noErr != result) {
...uh-oh...
}
// *now* we know that we have ioNumPackets worth of valid ASPDs,
// populated by the reader. and we have the associated audio data
// in other parameters.
// we can now safely pass all this information off to a function which
// reads the ASPDs, such as AudioFileWritePackets.
(knowing the OP's problem in some more detail) In many cases, you can avoid all this complexity and simply create an ExtAudioFile representation, and the specify kExtAudioFileProperty_ClientDataFormat for your destination sample format -- then the ExtAudioFile APIs will create an internal convertor on your behalf which will convert the input of an audio file of an arbitrary type to some specified PCM representation which you can use for the playback sample data. Implementing all this at this level is actually quite complex if you want to support many file formats. ExtAudioFile makes converting the sample data very easy -- if that is an option and if it plays nicely with your streaming scenario.
As far as the logging, well you're attempting to print the fields of a NULL structure, from the looks of it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is using repeatedly a function that outputs its arguments efficient?
I understand that the title of the question might seem a little confusing so I will try to present an example of the actual problem instance.
Consider the following code snippet:
f[args__, warg___] := Module[{i=1, x, v},
While[
b[args, i],
x = h1[args];
v = g[x, warg];
h2[v];
i++
]
]
For all intents and purposes, you may treat h1 and h2 as functions defined elsewhere (in effect, they are just a bunch of expressions defined in the body of f, preceding and following the evaluation of g). Also, b is just a boolean expression needed in While. It depends on input argument(s) and the value of a step counter i.
The function f (which is more-or-less the workhorse of my code) has a number of input parameters. The inputs are divided into two group.
The first group, denoted with args__ in the code, consists of all those parameters needed in subsequent computations.
The second group of inputs is denoted with warg___ ('w' for 'wildcard') and is actually a kind of switch.
When the warg parameter is present, function g executes and produces v (which is used in the rest of the code of f to produce the output). On the other hand, when the input argument warg is not present (the function f is called without it eg as in f[args], no warg present), function g- essentially-outputs its inputs ie x. Below is the (pseudo-)code definition for g.
g[arg_, warg_] := Module[{}
h3[arg, warg]
]
g[arg_] := arg
(Similarly, h3 is a shorthand for the body of g).
Now, where's the rub?
Well, the thing is that, although g is not expensive in terms of amount of computations performed, especially when it simply acts as a relay or an Identity transformation (spitting out x in the absence of warg), function f gets called a lot and g gets called that much more often (note how g is in a While loop in f).
So, I guess, the question is, if writing two separate versions of f (one including g and one simply calling h2[x] instead of v = g[x, warg] and then h2[v] in the case where warg is absent) would be more efficient than the current arrangement of using warg as a switch (and having the main loop try two different g's on for size every time). Obviously, in that former case, I would not need to have two definitions for g. Namely, the Identity transformation g[arg] := arg would not have a reason for being.
Having written down this question, and after some contemplation, I tend to favor the later approach (two f's, one g) for the simple reason that having the main loop decide which f to use many times is less expensive than doing the same thing for a lot more often with g, but I'd like to have a second opinion of more knowledgeable users.
As a post-script, please bear in mind that 'obsessing' over efficiency has to do with the fact that I'd like to port this code into a Manipulate at some point.
A:
Let's do a quick test:
ClearAll[g, h]
g[arg_, warg_] := h[arg, warg]
g[arg_] := arg
ClearAll[f1, f2]
f1[arg_, warg___] := g[arg, warg]
f2[arg_] := arg
10^# & /@ Range[5, 6];
% // AssociationMap@Function[{n},
First@Timing[# /@ Range[n]] & /@ {f1, f2}
]
<|100 000 -> {1.04688, 0.421875}, 1 000 000 -> {9.375, 3.29688}|>
(For the purposes of the test I stripped away all but the two different types of f's and g's.)
It seems the first method is a factor of roughly 2 or 3 slower.
Unfortunately there's tension between writing code that looks the nicest (and uses the full power of Mathematica) versus code that performs best. Luckily, at least in this case, it's not too bad, so you can often get away with using the more aesthetically pleasing code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular 4 CanActivate guard doesnt load component with used with service; simple Observable.of(true) works
I'm trying to use CanActivate guard in Angular it doesnt work when i call service from it and return true even return Observable.of(true);
But it works and load component when i dont call any service and just write
Observable.of(true); in canActivate
Following is the code doenst work :
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
//return Observable.of(true);
return this._userService.verify().subscribe((result: Array<Object>) => {
let user : UserDetail = new UserDetail();
Object.keys(user).forEach(key=>{
let listValue = result.filter(m=>m["m_type"]==key);
if(listValue.length>0){
user[key] = result.filter(m=>m["m_type"]==key)[0]["m_value"];
}
});
this.userDetails = user;
return Observable.of(true);
//return true;
}, (error: any) => {
// error when verify so redirect to login page with the return url
this._router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return true;
}, () => {
console.log("auth.guard : completed.");
//return true;
return Observable.of(true);
});
Following code works :
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return Observable.of(true);
});
A:
Observable is not promise any return code in subscribe will not work. change code to this.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
//return Observable.of(true);
return this._userService.verify().switchMap((result: Array<Object>) => {
let user : UserDetail = new UserDetail();
Object.keys(user).forEach(key=>{
let listValue = result.filter(m=>m["m_type"]==key);
if(listValue.length>0){
user[key] = result.filter(m=>m["m_type"]==key)[0]["m_value"];
}
});
this.userDetails = user;
return Observable.of(true);
//return true;
}).catch(() => {
// error when verify so redirect to login page with the return url
this._router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return Observable.of(false);
});
when you do let x = this.observable.subscribe();
x is subscription but not observable.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to separate symbols from string?
If I have a string that contains currency symbols how can I separate the symbol from the string? Assume the symbol could be anywhere in the string (ie. front, back, after a space)
"$5" => "$", "5"
"50,000₩" => "₩", "50,000"
"€307" => "€", "307"
Is this possible using regex? Any pointers or suggestions would be appreciated!
A:
There might be a better way to do this, but
str.scan(/\w/).join('')
will give you the alphanumeric characters, and
str.scan(/\W/).join('')
will give you the non-alphanumeric characters.
\w is the same as [a-zA-Z0-9_] and \W is [^a-zA-Z0-9_].
Since you have "50,000₩" => "₩", "50,000" in your example, you might want:
str.scan(/[a-zA-Z0-9_,]/).join('')
Also, if you know that you'll only have numbers, str.gsub(/[^0-9,]/, '') will probably do fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
logic - checking if at least one field is not null
i have this code, and need help with the logic end. I would like for at least one field to not be null.
if(!empty($fileTypes) || !empty($fileSizes) || !empty($fileUploads) || !empty($features) || !empty($design) || !empty($other) || !empty($contact)) {
} else {
$error = 1;
}
A:
Yes apologies the following works:
$array = array();
if($_POST){
foreach ($_POST as $key => $value){
if (!empty($value)){
$array[$key] = $value;
}
}
if (empty($array))
{
echo 'array empty';//throw error
} else {
echo 'array not empty'; //there is a submission
}
}
EDIT: Missed a closing tag in the paste....fixed
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I prompt Mac clients connecting to RDS/Terminal Services to change password at first login?
This is my first implementation of Remote Desktop Services/Terminal Services; we are using it as a solution for Mac clients that need to run a piece of new Windows-only software.
My question is about streamlining the user installation process. We don't have a directory service that extends to the Windows Server at present, so I need to temporarily activate these accounts with an admin-defined password, and force the user to change their password at first login.
Unfortunately, the relevant checkbox in user management does not seem to be a workable solution... the Mac client as well as the windows RDP client fail to log in.
(Perhaps I am missing something here? We only have the RD Session Host installed so far; I'm not sure what the purpose of the Gateway Server is in our implementation. Maybe one of these solve the password reset issue? I am using the new "Microsoft Remote Desktop" client available from the App Store, but see the same behavior with the old RDC app.)
Ideally I would like the user to be able to log in with my provided credentials, and be immediately prompted with a password change dialog. I already have a batch file running at first login, and was hoping for something that could be implemented there... the farthest I've gotten is control /name Microsoft.UserAccounts, but I'm unable to figure out how to drill down into the "Change your password" screen.
I was also considering net User %USERNAME% * until I realized that has to be run as Admin, which the batch file is not.
It's almost certainly going to be difficult to extricate myself from the client setup process in the first place, so one final alternative I've been considering is to randomly generate secure passwords on my own, and save the user's to his or her OS X Keychain when I install -- effectively making the server login transparent.
Any wisdom from more experienced admins about how I should go about this?
A:
The only thing here preventing the "automated" password change is the requirement for Network-Level Authentication. As long as the Remote Desktop server allows connections without NLA, the password changing functionality will work fine in either the Mac or Windows clients.
The client can still connect using NLA once the password has been changed, but the password change itself requires that a session begin without having been authenticated--NLA takes place before the session begins, and must use a valid login. Logins marked "User must change password at next logon" are considered expired, i.e. not valid, so they cannot be used to Network-Level Authenticate a session.
To allow non-NLA sessions, open RD Session Host Configuration and double-click the RDP-Tcp connection. The checkbox for NLA is in the security Section of the General tab.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting up the name of a file in the executable directory in C
I have to create a buffer to hold the the name of a license file which is in the executable directory. This is my solution (I'm not a C programmer):
char buffer[MAX_PATH] = "";
GetModuleFileName(NULL, buffer, MAX_PATH);
int len = (int) strlen(buffer);
buffer[len-7] = '\0';
strcat(buffer,"license.lic");
Note I know the name of the executable is net.exe - 7 chars, so I'm cheating.
Firstly is this code safe? I got a compiler warning about using strcat saying I should use strcat_s, but I couldn't get that working.
Secondly how do I get the correct length of the executable name?
A:
Your code is reasonably safe. Assuming MAX_PATH is the maximum possible length of a pathname, replacing the executable name with license.lic should fit in that size.
Rather than getting the length of the executable name, you can search for the last directory delimiter character, and copy license.lic after it. C has a built-in function strrchr() for searching a string in reverse.
char *sepptr = strrchr(buffer, '\\');
if (sepptr == NULL) {
sepptr = buffer; // no directory delimiter, replace it completely
} else {
sepptr++; // point to just past the delimiter
}
strcpy(sepptr, "license.lic"); // Overwrite executable name with license name
| {
"pile_set_name": "StackExchange"
} |
Q:
Newbie Python: Cannot Count Files in a Folder is there is a SPACE in name
I am running a script that attempts to recursively run through a folder of files and count how many of the given file types there are. It works swimmingly when there are no SPACES in the folder name. Why is this? What is a good way to fix this? Thank you!
import os
import fnmatch
def getPath():
path = raw_input("Drag file/enter filepath here: ")
return path
def convert():
patterns = ['*.wav', '*.aif', '*.aiff', '*.flac', '*.alac']
count = 0
for index in patterns:
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, index):
inputName = os.path.join(root, filename)
print inputName
count = count + 1
print count
rootPath = getPath()
convert()
A:
Try the solution in this other question. Define another function:
def shellquote(s):
return "'" + s.replace("'", "'\\''") + "'"
Then, when you've captured path within getPath(), do
new_path = shellquote(path)
and return new_path instead of path.
When you drag the file in or write a path with spaces, you need to either escape the spaces or put the whole path in quotes so it's clear that it's one single string. The shellquotes() function achieves both.
| {
"pile_set_name": "StackExchange"
} |
Q:
Gwt application does not appear in IE7
I created a gwt application....
It runs under current Chrome, FIlefox,Opera, IE8
but it does not work under IE7 at least on certain machines.
It means the embedded gwt application is not visible at all.
There is no javascript error. (Checked with Web Visual Studio) The version of IE is 7.0.6001.18000. The javascript is turned on.
It did not work on one machine and it does work on my machine inside IETESTER.
The program does not use ie7 specific code.
Is it known bug? Is gwt not ok with ie7?
What may be the reason?
A:
Make sure that you have not set your user.agent property to exclude ie in xxxxx.gwt.xml.
For example <set-property name="user.agent" value="gecko"/> will only compile javascript for firefox and this application will not run properly on an IE environment when deployed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Solving Multiple Equations For Repeated Times With Different Initial Conditions Matlab
I have the following set of values in an array.
a = [a(1) a(2) ... a(1907)]
Gamma(1)= (u*f(1))+(r*a(1))
u and r are constant and f(n) changes during each step and its initial value is f(1) = zero.
f(n) next values will be generated from solving these equations.
h(1) = x(1) + Gamma(1) for which x(1)=0 and in next steps is constant. (c)
Z(1)= constant(T) * h(1)
f(2) = constant(G) * Z(1)
These steps will repeated 1907 times. Any idea what should I do at all?
A:
You can input your initial conditions into a very simple for loop.
% a, u, r, T, G are assumed available.
f = zeros(1908, 1);
Z = zeros(1907 ,1);
Gamma = zeros(1907, 1);
x = [0; c*ones(1906, 1)];
for ii = 1:1907
Gamma(ii) = u*f(ii) + r*a(ii);
h(ii) = x(ii) + Gamma(ii);
Z(ii) = T*h(ii);
f(ii+1) = G*Z(ii);
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Generate pairs of students from list of names, new pairs each week
I have a list of students names, and I want to pair each student with another student every week. Obviously, students can only be in one pair each week, and students should never work with someone they already worked with previously. I can generate a list of tuples of every possible pair I can make with my list of student names, but I am struggling to take those pairs and generate lists of pairs for each week.
A:
What you're asking for is the scheduling algorithm for a round robin tournament. Here's one way to implement that in Python:
def round_robin(n):
if n % 2:
raise ValueError("Can't pair an odd number of students")
half = n // 2
students = list(range(1, n + 1))
for round in range(n - 1):
students.append(students.pop(1))
pairs = list(zip(students[:half], students[:half-1:-1]))
print(pairs)
And here it is in action:
>>> round_robin(8)
[(1, 2), (3, 8), (4, 7), (5, 6)]
[(1, 3), (4, 2), (5, 8), (6, 7)]
[(1, 4), (5, 3), (6, 2), (7, 8)]
[(1, 5), (6, 4), (7, 3), (8, 2)]
[(1, 6), (7, 5), (8, 4), (2, 3)]
[(1, 7), (8, 6), (2, 5), (3, 4)]
[(1, 8), (2, 7), (3, 6), (4, 5)]
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Function number doesn't affect how many times it runs?
If I write:
def f(n):
blah
f(x)
Then as long as 'x' is a number, f will run exactly once. e.g. I just tried:
def f(n):
c = 1
print c
f(x)
With 'x' as 0 and then 10, and the output was '1' both times. What does the number 'x' actually represent, and how do I get the function to run 'x' number of times?
I've solved my problem now with a workaround (I was going to post this question earlier but apparently I'm restricted to posting every 90 minutes) but I'd still like to know for future.
My program looked similar to this:
def f(n):
m = 0
c = blah
if condition(c):
m = 1
d = line involving c that had to be run before the end of the function loop, but after the if statement
f(m)
f(1)
But the output kept looping because even though m = 0, f(0) still caused the function to loop. My workaround was:
m = 0
def f(n):
global m
m = 0
c = blah
if condition(c):
m = 1
else:
m = 0
d = line involving c that had to be run before the end of the function loop, but after the if statement
if m = 1:
f(1)
f(1)
Which worked fine (and actually, looking back at it, I don't think 'd' did need to be run after the if statement, so I could've just done if condition(c): f(1)), but it seemed redundant. I'm not sure why I have to specify a number for f(n), but if I leave it blank or input a string it fails to run. Is there a less 'clumsy' fix to this?
(I'm really new to programming, so please explain in fairly simple terms..!)
Thanks!
A:
If you want something to run a number of times, you just need to code up a loop of some description. For a known-in-advance quantity, you can use for:
def f(n):
for i in range(n):
print i+1, "Pax is awesome"
print
x = 3
f(x)
f(x-1)
f(7)
Running that code will give you:
1 Pax is awesome
2 Pax is awesome
3 Pax is awesome
1 Pax is awesome
2 Pax is awesome
1 Pax is awesome
2 Pax is awesome
3 Pax is awesome
4 Pax is awesome
5 Pax is awesome
6 Pax is awesome
7 Pax is awesome
If you want to loop until a general condition is met (rather than a fixed number of times), you can use while rather than for:
def f(n):
while (n % 8) != 0:
print n, "Pax is awesome"
n += 1
f(3)
This loop will continue running until n reaches a multiple of eight:
3 Pax is awesome
4 Pax is awesome
5 Pax is awesome
6 Pax is awesome
7 Pax is awesome
Your workarounds seem a little strained, especially in the sense that they use wholly unnecessary recursion.
You should aim for clarity of code as your primary goal (I call this optimising for readability). Doing so will make your code less likely to contain bugs, and easier to maintain down the track.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find program's code address at runtime?
When I use gdb to debug a program written in C, the command disassemble shows the codes and their addresses in the code memory segmentation. Is it possible to know those memory addresses at runtime? I am using Ubuntu OS. Thank you.
[edit] To be more specific, I will demonstrate it with following example.
#include <stdio.h>
int main(int argc,char *argv[]){
myfunction();
exit(0);
}
Now I would like to have the address of myfunction() in the code memory segmentation when I run my program.
A:
Above answer is vastly overcomplicated. If the function reference is static, as it is above, the address is simply the value of the symbol name in pointer context:
void* myfunction_address = myfunction;
If you are grabbing the function dynamically out of a shared library, then the value returned from dlsym() (POSIX) or GetProcAddress() (windows) is likewise the address of the function.
Note that the above code is likely to generate a warning with some compilers, as ISO C technically forbids assignment between code and data pointers (some architectures put them in physically distinct address spaces).
And some pedants will point out that the address returned isn't really guaranteed to be the memory address of the function, it's just a unique value that can be compared for equality with other function pointers and acts, when called, to transfer control to the function whose pointer it holds. Obviously all known compilers implement this with a branch target address.
And finally, note that the "address" of a function is a little ambiguous. If the function was loaded dynamically or is an extern reference to an exported symbol, what you really get is generally a pointer to some fixup code in the "PLT" (a Unix/ELF term, though the PE/COFF mechanism on windows is similar) that then jumps to the function.
A:
If you know the function name before program runs, simply use
void * addr = myfunction;
If the function name is given at run-time, I once wrote a function to find out the symbol address dynamically using bfd library. Here is the x86_64 code, you can get the address via find_symbol("a.out", "myfunction") in the example.
#include <bfd.h>
#include <stdio.h>
#include <stdlib.h>
#include <type.h>
#include <string.h>
long find_symbol(char *filename, char *symname)
{
bfd *ibfd;
asymbol **symtab;
long nsize, nsyms, i;
symbol_info syminfo;
char **matching;
bfd_init();
ibfd = bfd_openr(filename, NULL);
if (ibfd == NULL) {
printf("bfd_openr error\n");
}
if (!bfd_check_format_matches(ibfd, bfd_object, &matching)) {
printf("format_matches\n");
}
nsize = bfd_get_symtab_upper_bound (ibfd);
symtab = malloc(nsize);
nsyms = bfd_canonicalize_symtab(ibfd, symtab);
for (i = 0; i < nsyms; i++) {
if (strcmp(symtab[i]->name, symname) == 0) {
bfd_symbol_info(symtab[i], &syminfo);
return (long) syminfo.value;
}
}
bfd_close(ibfd);
printf("cannot find symbol\n");
}
A:
To get a backtrace, use execinfo.h as documented in the GNU libc manual.
For example:
#include <execinfo.h>
#include <stdio.h>
#include <unistd.h>
void trace_pom()
{
const int sz = 15;
void *buf[sz];
// get at most sz entries
int n = backtrace(buf, sz);
// output them right to stderr
backtrace_symbols_fd(buf, n, fileno(stderr));
// but if you want to output the strings yourself
// you may use char ** backtrace_symbols (void *const *buffer, int size)
write(fileno(stderr), "\n", 1);
}
void TransferFunds(int n);
void DepositMoney(int n)
{
if (n <= 0)
trace_pom();
else TransferFunds(n-1);
}
void TransferFunds(int n)
{
DepositMoney(n);
}
int main()
{
DepositMoney(3);
return 0;
}
compiled
gcc a.c -o a -g -Wall -Werror -rdynamic
According to the mentioned website:
Currently, the function name and offset only be obtained on systems that use the ELF
binary format for programs and libraries. On other systems, only the hexadecimal return
address will be present. Also, you may need to pass additional flags to the linker to
make the function names available to the program. (For example, on systems using GNU
ld, you must pass (-rdynamic.)
Output
./a(trace_pom+0xc9)[0x80487fd]
./a(DepositMoney+0x11)[0x8048862]
./a(TransferFunds+0x11)[0x8048885]
./a(DepositMoney+0x21)[0x8048872]
./a(TransferFunds+0x11)[0x8048885]
./a(DepositMoney+0x21)[0x8048872]
./a(TransferFunds+0x11)[0x8048885]
./a(DepositMoney+0x21)[0x8048872]
./a(main+0x1d)[0x80488a4]
/lib/i686/cmov/libc.so.6(__libc_start_main+0xe5)[0xb7e16775]
./a[0x80486a1]
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom tableview cell with 6 imageviews
I have a very difficult problem. This is how my custom cell looks like.
|--------------------------------------------------------------------------|
| |
| |
| Imageview1 Imageview2 Imageview3 Imageview4 imageview5 |
| |
| |
| |
|--------------------------------------------------------------------------|
I have a core database with 20 images. What I want to do is to fill up all these imageviews with my images. So at the and I should have 5 rows with in each imageview a different image.
Here is my code for my cellforrowAtIndexpath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
for(int i=0;i<5;i++)
{
float xCoord = 0.0;
Team *team = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:team.image]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
UIImageView* imgView = [[UIImageView alloc] initWithImage:image];
[imgView setFrame:CGRectMake(xCoord,0,imgView.frame.size.width, imgView.frame.size.height)];
[cell.contentView addSubview:imgView];
xCoord += imgView.frame.size.width;
}
return cell;
}
This is how far i got. I don't now how to fill up this tableview correctly. The other imageviews are name img_Player2,img_Player3,img_Player4,img_Player5.
Can anybody help?
Thank you
SCREENS WITH WHAT I WANT TO ACHIEVE
This is what I want to achieve:
And at the moment I have this.
A:
You need to add the UIImageViews to the contentView of the UITableViewCell. Let's assume your 5 images are loaded in an NSArray called imagesArray. For simplicity I'm assuming each of your images is 64 (320/5) pixels wide and 44 pixels high.
Your code inside cellForRowAtIndexPath should roughly look like this:
float xCoord = 0.0;
for (UIImageView *imgView in imagesArray)
{
[imgView setFrame:CGRectMake(xCoord,0,imgView.frame.size.width, imgView.frame.size.height)];
[cell.contentView addSubview:imgView];
xCoord += imgView.frame.size.width;
}
Your code will be this:
float xCoord = 0.0;
for(int i=0;i<5;i++)
{
Team *team = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:team.image]];
UIImageView* imgView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:imageData]];
[imgView setFrame:CGRectMake(xCoord,0,imgView.frame.size.width, imgView.frame.size.height)];
[cell.contentView addSubview:imgView];
xCoord += imgView.frame.size.width;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
UIButton with title under the imageview
I want to creat an UIButton programmatically with the title under the imageView.
Size of the button : 170 * 120
Size of the imge : 50 * 50
Size of the title : depend of the text.
I know I'have to use but I don't know how :
[_button setTitleEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)];
[_button setImageEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)];
I think I should calculate the size of the title and then Use the EdgeInsets.
Thank you.
A:
Hope this can help you.
@interface UIButton (UIButtonExt)
- (void)centerImageAndTitle:(float)space;
- (void)centerImageAndTitle;
@end
@implementation UIButton (UIButtonExt)
- (void)centerImageAndTitle:(float)spacing
{
// get the size of the elements here for readability
CGSize imageSize = self.imageView.frame.size;
CGSize titleSize = self.titleLabel.frame.size;
// get the height they will take up as a unit
CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);
// raise the image and push it right to center it
self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);
// lower the text and push it left to center it
self.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (totalHeight - titleSize.height),0.0);
}
- (void)centerImageAndTitle
{
const int DEFAULT_SPACING = 6.0f;
[self centerImageAndTitle:DEFAULT_SPACING];
}
@end
A:
The ultimate and stable solution is to use frame, not EdgeInset solution like this:
@interface UIButton (UIButtonExt)
(void)centerImageAndTitleEx;
@end
@implementation UIButton (UIButtonExt)
(void)centerImageAndTitleEx
{
CGRect frame = self.imageView.frame;
frame = CGRectMake(truncf((self.bounds.size.width - frame.size.width) / 2), 10.0f, frame.size.width, frame.size.height);
self.imageView.frame = frame;
frame = self.titleLabel.frame;
frame = CGRectMake(truncf((self.bounds.size.width - frame.size.width) / 2), self.bounds.size.height - frame.size.height - 5.0, frame.size.width, frame.size.height);
self.titleLabel.frame = frame;
}
@end
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I set up VLAN forwarding?
I have a DAAP server with multiple VLAN interfaces. I would like to get traffic forwarded on all of the VLANs. Forwarded from eth0 to eth1.010* I've got the switch configured to be a trunk port with the correct VLANs, and I enabled /proc/sys/net/ipv4/ip_forward
But that doesn't seem to be doing the trick.
Is there anything else I need to do?
Here is my ifconfig results, as you can see the VLAN interfaces aren't really getting any traffic:
eth0 Link encap:Ethernet HWaddr 00:14:d1:10:ca:fc
inet addr:192.168.1.20 Bcast:172.21.255.255 Mask:255.255.0.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:536 errors:0 dropped:0 overruns:0 frame:0
TX packets:259 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:264232 (258.0 KiB) TX bytes:37425 (36.5 KiB)
Interrupt:20 Base address:0xe000
eth1 Link encap:Ethernet HWaddr 00:1c:c4:31:28:22
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:303 errors:0 dropped:0 overruns:0 frame:0
TX packets:202 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:225213 (219.9 KiB) TX bytes:47118 (46.0 KiB)
Interrupt:17
eth1.0101 Link encap:Ethernet HWaddr 00:1c:c4:31:28:22
inet addr:172.17.1.20 Bcast:172.17.1.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:40 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:9076 (8.8 KiB)
eth1.0102 Link encap:Ethernet HWaddr 00:1c:c4:31:28:22
inet addr:172.18.1.20 Bcast:172.18.1.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:40 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:9076 (8.8 KiB)
eth1.0103 Link encap:Ethernet HWaddr 00:1c:c4:31:28:22
inet addr:172.19.1.20 Bcast:172.19.1.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:40 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:9076 (8.8 KiB)
eth1.0104 Link encap:Ethernet HWaddr 00:1c:c4:31:28:22
inet addr:172.20.1.20 Bcast:172.20.1.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:40 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:9076 (8.8 KiB)
eth1.0105 Link encap:Ethernet HWaddr 00:1c:c4:31:28:22
inet addr:172.21.1.20 Bcast:172.21.1.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:40 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:9076 (8.8 KiB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:113 errors:0 dropped:0 overruns:0 frame:0
TX packets:113 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:20777 (20.2 KiB) TX bytes:20777 (20.2 KiB)
Here is my /etc/network/interfaces file:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback
# Automagically configured network interfaces
auto eth0
auto eth1.0101
auto eth1.0102
auto eth1.0103
auto eth1.0104
auto eth1.0105
iface eth0 inet static
address 192.168.1.20
netmask 255.255.0.0
gateway 192.168.1.3
network 172.21.0.0
broadcast 172.21.255.255
iface eth1.0101 inet static
address 172.17.1.20
netmask 255.255.255.0
iface eth1.0102 inet static
address 172.18.1.20
netmask 255.255.255.0
iface eth1.0103 inet static
address 172.19.1.20
netmask 255.255.255.0
iface eth1.0104 inet static
address 172.20.1.20
netmask 255.255.255.0
iface eth1.0105 inet static
address 172.21.1.20
netmask 255.255.255.0
Thank you for any help, I've been working on this for quite a while.
A:
I haven't done this on Ubuntu but here's my research so far:
You need to stick
vconfig add eth1 101
vconfig add eth1 102
vconfig add eth1 103
vconfig add eth1 104
vconfig add eth1 105
in a startup script.
The interfaces file would look something like this:
auto lo
iface lo inet loopback
auto eth0 eth1 vlan2 vlan3 vlan4 vlan5
iface eth0 inet dhcp
# VLAN 1 - native management VLAN
iface eth1 inet static
address 10.0.0.1
netmask 255.255.255.224
vlan_raw_device eth1
# VLAN 2 - DMZ
iface vlan2 inet static
address 10.0.0.33
netmask 255.255.255.224
vlan_raw_device eth1
# VLAN 3 - Accounting
iface vlan3 inet static
address 10.0.0.65
netmask 255.255.255.224
vlan_raw_device eth1
# VLAN 2 - DMZ
iface vlan2 inet static
address 10.0.0.33
netmask 255.255.255.224
vlan_raw_device eth1
# VLAN 3 - Accounting
iface vlan3 inet static
address 10.0.0.65
netmask 255.255.255.224
vlan_raw_device eth1
# VLAN 4 - Engineering
iface vlan4 inet static
address 10.0.0.97
netmask 255.255.255.224
vlan_raw_device eth1
# VLAN 5 - Sales & Marketing
iface vlan5 inet static
address 10.0.0.129
netmask 255.255.255.224
vlan_raw_device eth1
You will use your own IPs in the interfaces file, obviously.
Let us know if it worked.
References:
1
2
A:
It worked! I've got a separate problem with DAAP now, but I think it's Avahi related. I'll try to work through that myself. Thanks a ton.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is this called in F# when a type appears after a specified type?
I have seen examples like this:
type OptionalString = string option
type customers = customer list
In these example both option and list type appears after string and customer types.
Is there documentation that I can find that shows all the list of types that can be written like this?
Also is this similar to <> in c#?
A:
This is described in the specification [pdf]:
5.1.1 Named Types
Named types have several forms, as listed in the following table
type long-ident Named type with one type argument; processed the same
as long-ident<type>
so you can use this form for generic types with a single parameter. This works for user-defined types e.g.
type Test<'a> = Test of 'a
let x : int Test = Test(3)
| {
"pile_set_name": "StackExchange"
} |
Q:
Switch case with Select Option
I'm having problems to set a Switch Case with the value of a Select options, here's the code I'm using:
<form id="selectcub" name="selectcub">
<select id="cub01" name="cub01" class="cub">
<option value="2013" selected>2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
</select>
<select id="cub02" name="cub02" class="cub">
<option value="01">01</option>
<option value="02">02</option>
<option value="03" selected>03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<a id="cubdl" href="#" class="button">Open</a>
</form>
<script type="text/javascript">
$(document).ready(function(){
switch($('#cub02 option:selected').val()) {
case 01:
alert("I am an alert box! 1");
break;
case 02:
alert("I am an alert box! 2");
break;
default:
//
}
});
</script>
What am I doing wrong? Here is a live demo: http://jsfiddle.net/whC97/
A:
val() is always going to return a string. Try putting "01", "02", etc. in your switch statement.
A:
The problem is that you are binding to $(document).ready(), and not on the click of your link. So the javascript is checking the value on load, and the value is 03 for which you don't have any case.
If you change the default selected on 01 and put the cases in quotes you can see it works alright.
| {
"pile_set_name": "StackExchange"
} |
Q:
Jmockit @Mocked inside a helper class doesn't initialize
If I have the following;
public class ClassA {
public void methodA(){
System.out.println("In ClassA, methodA");
}
}
public class ClassB {
public void methodB(){
}
}
and a junit test of;
@Test
public void testMocked(@Mocked final ClassB mockedB) {
System.out.println("Mocked inline");
new MockUp<ClassA>() {
@Mock
public void methodA() {
System.out.println("Inline mockup, mockedB:" + mockedB);
}
};
ClassA a = new ClassA();
a.methodA();
}
Then when I run the test I get;
Mocked inline
Inline mockup, mockedB:jmockitpractice.ClassB@329b0985
Which is as expected, the classB is Mocked, and an instance is available.
But, if I change this to create a helper class for mocking,
public class MockHelper {
@Mocked ClassB classB;
public void setupMocks(){
new MockUp<ClassA>() {
@Mock
public void methodA(){
System.out.println("In setupMocks, classB:"+classB);
}
};
}
}
and the junit becomes;
@Test
public void testMockedInClass() {
System.out.println("Mocked in helper class");
MockHelper mh = new MockHelper();
mh.setupMocks();
ClassA a = new ClassA();
a.methodA();
}
the result I get is;
Mocked in helper class
In setupMocks, classB:null
classB is not initialized by the @Mocked inside MockHelper
I would like to have all the mocking in a helper class, rather than having to declare all the mocking in the test class.
Any ideas why this doesn't work?
Thanks.
A:
Thanks Dom Farr, the answer was inheritance.
public class MockHelper {
@Mocked
ClassB classB;
public void setupMocks() {
new MockUp<ClassA>() {
@Mock
public void methodA() {
System.out.println("In setupMocks, classB:" + classB);
}
};
}
}
and
public class mockTest extends MockHelper {
@Test
public void testMockedInClass() {
System.out.println("Mocked in helper class");
setupMocks();
ClassA a = new ClassA();
a.methodA();
}
}
As the test class extends the helper, it now works;
Mocked in helper class
In setupMocks, classB:jmockitpractice.ClassB@5d54e317
| {
"pile_set_name": "StackExchange"
} |
Q:
Makefile skips dependency
I've created a makefile for my little project
.SUFFIXES:
%.cpp:
$(COMP) -c -o $(subst .cpp,.o,$@) $(SRCDIR)$@ $(CFLAGS)
platformL: COMP:=gcc
platformL: $(FILES)
$(COMP) -o $(NAME) $(subst .cpp,.o,$(FILES)) $(CFLAGS)
rm $(subst .cpp,.o,$(FILES))
platformW: COMP:=wine gcc
platformW: $(FILES)
$(COMP) -o $(NAME).exe $(subst .cpp,.o,$(FILES)) $(CFLAGS)
rm $(subst .cpp,.o,$(FILES))
default: platformL platformW
echo Done!
Everything worked fine until I branched to 2 different platforms, 'make' command executes only my platformL branch. After spending some time with it I discovered that adding '.PHONY' won't fix the problem. Also, it appears that only the first branch from the top gets executed (I have put the lines of platformW before platformL and only Windows compilation was performed).
How can I make it execute both branches?
A:
Make always builds the first explicit target (and all prerequisites of the first explicit target) in the makefile, by default. That's all it will build by default.
You can either specify multiple things to build on the command line, like make platformL platformW, or you can add a new first target that depends on all the other targets you want built. By tradition that target is named all but you can call it whatever you want:
all: platformL platformW
.PHONY: all
...
platformL: ...
...
platformW: ...
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make custom colored paper
I love making a craft made from paper. Currently I have difficulty to find colour specific paper such Teal coloured paper. I expect I will get the same issue when I need specific coloured paper since I have my favourite colours got from my Pantone colour sheet and I want to use some of their colours.
Is there a way to dye paper and get the near-accurate result?
im going to use it for origami
A:
You can create colored paper pulp by running colored craft paper through a blender. An alternative is to add food color or paint (or tea, or any other stain or coloring agent) to white paper pulp. Once you have several jars with different colored pulps, you can then blend those colors together to make the color you desire to use in your paper. The final color of the pulp will shift slightly as it dries when you make the paper, sort of like the shift in color between wet and dry paint. Some practice is needed to get the precise final color you desire.
The following video shows how to mix colored paperpulp when making paper:
https://www.youtube.com/watch?v=XCjLGX6W48Q
| {
"pile_set_name": "StackExchange"
} |
Q:
What Virtual Machines run on both OSX and Ubuntu?
For developing web applications I run a development environment on OSX, this environment includes Django and apache with mod_wsgi. My staging server and production server are both virtual machines using KVM, running Ubuntu (10.04) with apache, mod_wsgi, mysql, solr on jetty.
As a result bringing new versions from staging to production server is hassle-free, just copy the VM from staging to production. Going from development to staging is painful though.
So may question is :
is there a way to use a VM running ubuntu on my mac that can be (easily) exported to a VM running on linux?
I've briefly looked into Virtual Box, but it's unclear to me if there's a reasonable chance this will work. Other stuff like virtuozzo/openVZ doesn't run on OSX apparantly.
A:
VirtualBox runs fine on both MacOS X and Ubuntu. You can easily export/import appliances (ovf) from them. http://www.virtualbox.org/manual/ch01.html#ovf
A:
It's not free, but if you virtualise using Fusion from VMware, it will allow you to export your VM from the Mac to virtually any VMware product - for instance Workstation or Server running on Linux.
Alternatively your Linux virtualisation solution of choice may be able to import VMware VMs - for instance if you are using Virtualbox see http://www.ubuntugeek.com/howto-convert-vmware-image-to-virtualbox-image.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Is "native" always considered offensive, when referring to a person who lived in a place originally?
When I read the definition of native in the OALD, I see the following:
(old-fashioned, offensive) a word used in the past by Europeans to describe a person who lived in a place originally, before white people arrived there
I remember that, when speaking with a friend of mine (American) about the people Columbus called indiani, I was said I should refer to them as American natives.
Is native always considered offensive, or is American natives the exception to the rule?
A:
Actually the phrase is not "American natives" but "Native Americans".
I think what the writer of that definition was trying to say was that the word "native" as a stand-alone noun to mean a person from a non-Western culture with a low level of technology is now considered offensive. Like if you drew a picture of a group of people standing in front of a mud hut, with painted faces and carrying spears, and labeled it "Natives", this would be considered offensive.
The word "native" in general simply means some one or thing that originally comes from a particular place. In this sense it is a perfectly good word. I certainly would not be offended if you referred to me as "a native of New York". We routinely talk about "foods native to the region", about a person's "native language", etc.
But anyway, I don't think there's any simple rule as to what makes a word or phrase offensive. When I was a boy in the 1960s, members of a certain ethnic group were routinely referred to as "negroes". Then about the 1970s or so we were told that this term was offensive, and that we should call them "black". Then in the 1990s we were told that "black" is offensive, and we should call them "African-American". How did "black" go from being the polite term to being offensive? It just did. There's no pattern to such things.
I saw a survey a few years back that found that a majority of American Indians prefer to be called Indians rather than Native Americans. For that matter, I saw a survey fairly recently where they asked black people what they prefer to be called, and 1% said "African Americans", 2% said "black", 96% said "don't care", and there was the usual scattering of other answers.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to migrate Wordpress Blogs into Multisite without using the GUI-Import/Export Feature
I'd like to migrate some quite huge Wordpress-Blogs into one Multisite Installation.
The Export-Wizard and the Import Wizard are bound to PHP-Limits (Memory, Execution-Time) and so the Export and Import often fails.
There must be a way to do it by hand (only using MySQL and or the command line).
A:
http://bavatuesdays.com/importing-a-single-wp-blog-to-a-wpmu-installation/
http://sillybean.net/wordpress/migrating-single-wordpress-installations-into-multisite-networks/
| {
"pile_set_name": "StackExchange"
} |
Q:
SVN Update but ignore certain revisions
What I am trying to do I don't think the SVN:ignore command is going to do what i want it do.
I have an SVN repository which is the same application deployed for a handful of seperate clients. I have made changes to a group of files, but only one of the clients (client A we'll call them) wants these changes (they want their web app to be accessible in an iframe, whilst the others don't).
I don't want to just ignore the files on the other servers because in the future I will be making modifications to those files that they need.
Essentially for everyone that isn't client A i need to update their server but not update any of the changes on revision x which are only for client A.
I don't even know if this is possible because in the future it would be very easy to overwrite those files wouldn't it? I would forever have to be remembering to ignore that revision wouldn't I?
If it isn't possible, are there any other workarounds people have used? One method I thought but can't seem to get working the way i thought it would in theory is to merge those changes for Client A's server into a different branch, but then I will have to maintain a different repository branch each time a client wants something different from the other clients?
A:
To be a bit contrarian here, I don't think branches or tags are the correct solution to your problem, unless you have an infinite amount of time to merge code between development lines.
A different approach is a monolithic code base where you adapt a superset of features for all your clients. For each client, you configure features on and off. (Your configuration for each client is separate from your codebase, right?) Even if you have different paths your code follows for each client, you get the benefit of being able to fix common features once.
Additionally, as you develop varied features for each client, you have the opportunity to sell a client a feature that's potentially already built. All you need to do is configure it on.
Granted, if the needs of each of your clients is vastly different, this solution may not work. However, since you're keeping the codebase in the same repo, I'm going to assume it is.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to use my Raspberry Pi as an ethernet to USB adapter?
I am trying to install various linux distros on my MacBook Air and MacBook Pro machines. They often require an ethernet connection for the installation. Instead of paying for and waiting for an adapter (because the Mac machines do not have ethernet ports), is there a way I could use my Pi in the place of an adapter? I have a Raspberry Pi 3 B+ btw.
A:
No! The USB (which is a Hub) cannot act as a host. It may be possible with a Zero or A, but even this is impracticable.
But then your question is predicated on falsehood - you DO NOT require an ethernet connection for installation. You can easily install from an image on USB, but this is not a Pi question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Objective-C character encoding - Change char to int, and back
Simple task: I need to convert two characters to two numbers, add them together and change that back to an character.
What I have got: (works perfect in Java - where encoding is handled for you, I guess):
int myChar1 = (int)([myText1 characterAtIndex:i]);
int myChar2 = (int)([myText2 characterAtIndex:keyCurrent]);
int newChar = (myChar1 + myChar2);
//NSLog(@"Int's %d, %d, %d", textChar, keyChar, newChar);
char newC = ((char) newChar);
NSString *tmp1 = [NSString stringWithFormat:@"%c", newC];
NSString *tmp2 = [NSString stringWithFormat:@"%@", newString];
newString = [NSString stringWithFormat:@"%@%@", tmp2, tmp1]; //Adding these char's in a string
The algorithm is perfect, but now I can't figure out how to implement encoding properties. I would like to do everything in UTF-8 but have no idea how to get a char's UTF-8 value, for instance. And if I've got it, how to change that value back to an char.
The NSLog in the code outputs the correct values. But when I try to do the opposite with the algorithm (I.e. - the values) then it goes wrong. It gets the wrong character value for weird/odd characters.
A:
NSString works with unichar characters that are 2 bytes long (16 bits). Char is one byte long so you can only store code point from U+0000 to U+00FF (i.e. Basic Latin and Latin-1 Supplement).
You should do you math on unichar values then use +[NSString stringWithCharacters:length:] to create the string representation.
But there is still an issue with that solution. You code may generate code points between U+D800 and U+DFFF that aren't valid Unicode characters. The standard reserves them to encode code points from U+10000 to U+10FFFF in UTF-16 by pairs of 16-bit code units. In such a case, your string would be ill-formed and could neither be displayed nor converted in UTF8.
Also, the temporary variable tmp2 is useless and you should not create a new newString as you concatenate the string but rather use a NSMutableString.
| {
"pile_set_name": "StackExchange"
} |
Q:
Upload new iOS 10 application built by older Xcode 7
I've a simple question. What are requirements for new app upload to latest AppStore?I mean is it required to use latest Xcode 8 and also latest swift or is it possible to upload the new application running on swift 2.2 version using Xcode 8 or maybe with Xcode 7? I'm curios if apple states informations like that somewhere.
A:
Apple recommends you to build and submit to App store with latest SDK. However, it doesn't mean that it forces you to do that. In other words, you can use older SDK to compile you source code. For example, you can compile you app with XCode8 with Swift 3, but if you do with XCode7 and Swift 2.2, it's also fine.
Have a look at this: https://developer.apple.com/library/content/qa/qa1806/_index.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Identifying a set $S$ with a subset in $T$.
Let $S = \{1,2\} \subset \mathbb{N}$, and $T = \{5,6,7\} \subset \mathbb{N}$. Clearly, $S \not\subset T$.
Let $i:S \to \{5,6\}$ be such that $i(n) = n+4$. This is injective and surjective. So, $i$ is an isomorphism.
Then, can I "identify" $S$ with a subset of $T$ via $i$, and hence $S \subset T$? If yes, what is the mathematical machinary behind this? Are we using the equivalence relation "$n \sim i(n)$ for $n \in S$"?
A:
There is no actual mathematics behind this type of convention.
Any suppressed identification (such as $\Bbb R \subseteq \Bbb C$ as in the comments) is an abuse of notation, which aids our intuition because we can guess (or "intuitively know", if you prefer) what the identification/inclusion map $i: \Bbb R \hookrightarrow \Bbb C$ is.
This kind of "abuse" makes our life easier because it allows us to obfuscate trivialities and focus on the interesting stuff at hand.
For example, if $F' \subseteq F$ is a subfield, then we will usually use $+$ for both addition in $F'$ and in $F$. But then if we write $f_1 + f_2$ for $f_1,f_2 \in F'$, do we mean $+: F' \times F' \to F'$ or $+: F \times F \to F$? Obviously, it "doesn't matter", so we drop the distinction.
If you are interested in this kind of thing, consider having a look at category theory. Through making this type of identification explicit, it uncovers a lot of interesting results applicable in all of mathematics. Have a look at the concept of a "forgetful functor".
| {
"pile_set_name": "StackExchange"
} |
Q:
How safe is it for me to install Java on OS X 10.8
I know very little about how Java works and its interactions with OS X, so I'm partly looking for an expert and simple description on how Java works on the Mac, and why so much press includes "fear, uncertainty, doubt" but no concrete details about how and why Java is not safe..
I want to use the Bitcoin client Multibit, but to do so I will need to install Java which over the past six months I've only heard bad things about.
So my question is: How safe is it for me to install Java on Mac OS X 10.8.3?
(The hidden question inside this question is what version / source of Java I should select if I can depend on Apple to keep Java secure.)
I understand "safeness" is a fairly difficult thing to define, but just some general advice would be greatly appreciated. Even if someone could point me in the direction of some learning materials so I can work this out for myself, that would be great.
A:
The Java Runtime Environment (JRE) and the Java SDK are not inherently unsafe. The problem relies for the most part in certain ways the JVM (Java Virtual Machine) accesses (and can be fooled to) certain pieces of the operating system.
Like every other complex piece of software, Java is no different than, say, .NET on a Windows machine or Mono.NET on any flavor.
Java on a browser, however, is a different world (and hence why you can go ahead and disable it in most modern browsers), similar to (but not as bad as) what ActiveX was back in the days of Internet Explorer.
You can safely have the JRE in your Macintosh, Linux or Windows machine with little danger, since no element of the Java RE or SDK will expose remote vulnerabilities by default. It's just a lot of code sitting in your Hard Drive.
Now if you want to know if executing Java software is unsafe, then there's no way to answer that without diving into huge arguments. If you want to run Java Software, just go to Oracle, download the Runtime environment and run your Java program. It will not be activated by default on Safari (but double check to be sure) or any other browser.
With all that said, Java is annoying (especially their updater, which you can tone down or disable but never ceases to be as annoying or sometimes more than the Flash Updater if you have Flash). On the other hand, Oracle finally started rolling more periodic updates to Java so vulnerabilities are taken care more often (which is annoying but good). When Apple was in control of the SDK, this wasn't the case.
Of course, some "security experts" will cry out loud that having Java in your hard drive can lead to more insecurity since someone gains access to your computer, they could exploit local Java vulnerabilities. Trust me, if anyone gains access to your computer (even remote) to the point where they can execute anything (including Java), you have a bigger problem.
So if you need it, go ahead and get it.
A:
The Java exploits have been accessing through java on websites. You do not need to enable this e.g. in Safari you can set a preference to use Java or not.
If you have a command line java application (e.g. Bitcoin) this is then is as risky as an other application. You need to make sure you have the latest version of third party libraries and executables to keep up to date with security fixes.
A:
Yes, it is safe to install Java on you computer.
To answer your second question, is it safe to use http://multibit.org/ with Java for online transactions, the answer is use Caution as with any money transaction on the web.
The real question is about the Mulibit client as you pointed out. Multibit is not the safest out there so consider using others. Multibit connects directly to the network, and there could be your problem. Means you would have to keep the Multibit up to date, but that is no quarantine either.
http://bitcoinmagazine.com/bitcoin-wallet-options/
...There is also more specific website for this type of question here:
https://bitcoin.stackexchange.com/
Just to add my personal advice, I would caution you with such products, unless you are expert in keeping your computer safe.
It is your money!
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the hybridization of chlorine in vinyl chloride?
Is chlorine in vinyl chloride sp2 or sp3 hybridized?
Calculating using steric number it is found to be sp3 hybridized. But according to I. L. Finar* it is sp2.
*I.L. Finar: Organic chemistry Vol.1 Fundamental principles. Sixth Edition. Orient Longmans: 1973. Page 328.
A:
Disclaimer: An important point to remember is, that hybridisation always follows the molecular structure, it is never the cause for a certain structure. As such, hybridisation is an interpretation tool, nothing more.
As a rule of thumb, terminal atoms (excluding hydrogen) are almost always (maximally) approximately sp hybridised. While other hybridisation schemes can be applied, they are usually not a good representation.*
One popular example is water. In many texts the central oxygen is described as having (approximately) four sp3 orbitals, which essentially makes the lone pairs equivalent. That view, however, is not in agreement with the photoelectron spectrum, which clearly shows that the lone pairs are not equivalent. At this point I'd like to refer you to Michael Laing's article: "No rabbit ears on water. The structure of the water molecule: What should we tell the students?" (J. Chem. Educ. 1987, 64 (2), 124.).
The same principle described there applies to terminal atoms. Because of the local $C_\mathrm{\infty}$ symmetry the notion of three equivalent lone pairs is likely to be false. The most likely (main resonance contributor) structure for these atoms are (if hybridisation is at all feasible, i.e. mostly in the second period) one sp orbital forming the bond, one sp lone pair, two (perpendicular) p lone pairs.
In this particular example, I have calculated the molecule on the DF-BP86/def2-SVP level of theory and analysed it with the natural bond orbital theory (NBO6). Below you find the localised orbitals which best fit with the common Lewis structure of the molecule.
I have ordered the orbitals starting with the carbon-carbon σ- and carbon-chlorine σ-bonds on the bottom. Following that is the carbon-carbon π-bond. Continuing with the three carbon-hydrogen σ-bonds, and finally ending with the three chlorine lone pairs. The occupied orbitals are in blue and orange, while the corresponding virtual orbitals are next to it in red and yellow. The detailed analysis in numbers is at the end of the post.
In ast's answer there is the claim that chlorine must be sp2 hybridised because of a resonance contributor. While this explanation is extremely tempting because it easy to understand, you cannot judge from the possibility of resonance to the electronic structure. As another general rule of thumb you can remember: the lesser the orbitals are hybridised, the more likely the structure is.
The calculation also provides an analysis in terms of natural resonance theory. On the DF-BP86/def2-SVP level the contribution of the second configuration to the total electronic structure is only 6%. The main configuration contributes with about 90%, other configurations (ionic) make up the remaining 4%.
In summary, I'm afraid, but your book is incorrect, or at least incomplete. The description with two equivalent sp2 lone pairs is unnecessary complicated and does not accurately reproduce the electronic structure.
Truncated results of the NBO analysis (skipping core orbitals)
(Occupancy) Bond orbital / Hybrids
------------------ Lewis ------------------------------------------------------
8. (1.99378) LP ( 1)Cl 6 s( 81.55%)p 0.23( 18.44%)d 0.00( 0.01%)
9. (1.97199) LP ( 2)Cl 6 s( 0.18%)p99.99( 99.79%)d 0.18( 0.03%)
10. (1.90237) LP ( 3)Cl 6 s( 0.00%)p 1.00( 99.95%)d 0.00( 0.05%)
11. (1.99642) BD ( 1) C 1- C 2
( 48.61%) 0.6972* C 1 s( 0.00%)p 1.00( 99.94%)d 0.00( 0.06%)
( 51.39%) 0.7169* C 2 s( 0.00%)p 1.00( 99.95%)d 0.00( 0.05%)
12. (1.99535) BD ( 2) C 1- C 2
( 49.24%) 0.7017* C 1 s( 40.16%)p 1.49( 59.76%)d 0.00( 0.08%)
( 50.76%) 0.7124* C 2 s( 44.47%)p 1.25( 55.47%)d 0.00( 0.06%)
13. (1.96941) BD ( 1) C 1- H 3
( 61.15%) 0.7820* C 1 s( 29.81%)p 2.35( 70.15%)d 0.00( 0.04%)
( 38.85%) 0.6233* H 3 s( 99.91%)p 0.00( 0.09%)
14. (1.98105) BD ( 1) C 1- H 4
( 61.33%) 0.7832* C 1 s( 30.09%)p 2.32( 69.87%)d 0.00( 0.04%)
( 38.67%) 0.6218* H 4 s( 99.91%)p 0.00( 0.09%)
15. (1.98492) BD ( 1) C 2- H 5
( 62.36%) 0.7897* C 2 s( 32.79%)p 2.05( 67.18%)d 0.00( 0.03%)
( 37.64%) 0.6135* H 5 s( 99.89%)p 0.00( 0.11%)
16. (1.99056) BD ( 1) C 2-Cl 6
( 43.14%) 0.6568* C 2 s( 22.75%)p 3.39( 77.00%)d 0.01( 0.25%)
( 56.86%) 0.7541*Cl 6 s( 18.31%)p 4.43( 81.12%)d 0.03( 0.57%)
---------------- non-Lewis ----------------------------------------------------
17. (0.09516) BD*( 1) C 1- C 2
( 51.39%) 0.7169* C 1 s( 0.00%)p 1.00( 99.94%)d 0.00( 0.06%)
( 48.61%) -0.6972* C 2 s( 0.00%)p 1.00( 99.95%)d 0.00( 0.05%)
18. (0.01232) BD*( 2) C 1- C 2
( 50.76%) 0.7124* C 1 s( 40.16%)p 1.49( 59.76%)d 0.00( 0.08%)
( 49.24%) -0.7017* C 2 s( 44.47%)p 1.25( 55.47%)d 0.00( 0.06%)
19. (0.00909) BD*( 1) C 1- H 3
( 38.85%) 0.6233* C 1 s( 29.81%)p 2.35( 70.15%)d 0.00( 0.04%)
( 61.15%) -0.7820* H 3 s( 99.91%)p 0.00( 0.09%)
20. (0.01032) BD*( 1) C 1- H 4
( 38.67%) 0.6218* C 1 s( 30.09%)p 2.32( 69.87%)d 0.00( 0.04%)
( 61.33%) -0.7832* H 4 s( 99.91%)p 0.00( 0.09%)
21. (0.02582) BD*( 1) C 2- H 5
( 37.64%) 0.6135* C 2 s( 32.79%)p 2.05( 67.18%)d 0.00( 0.03%)
( 62.36%) -0.7897* H 5 s( 99.89%)p 0.00( 0.11%)
22. (0.03245) BD*( 1) C 2-Cl 6
( 56.86%) 0.7541* C 2 s( 22.75%)p 3.39( 77.00%)d 0.01( 0.25%)
( 43.14%) -0.6568*Cl 6 s( 18.31%)p 4.43( 81.12%)d 0.03( 0.57%)
Summary of Natural Population Analysis
Natural Population
Natural ---------------------------------------------
Atom No Charge Core Valence Rydberg Total
--------------------------------------------------------------------
C 1 -0.43992 1.99995 4.42868 0.01129 6.43992
C 2 -0.22801 1.99996 4.20978 0.01827 6.22801
H 3 0.22758 0.00000 0.76996 0.00246 0.77242
H 4 0.22498 0.00000 0.77165 0.00337 0.77502
H 5 0.23463 0.00000 0.76237 0.00300 0.76537
Cl 6 -0.01926 9.99998 7.00353 0.01575 17.01926
====================================================================
* Total * 0.00000 13.99989 17.94598 0.05414 32.00000
Optimised Geometry DF-BP86/def2-SVP
6
symmetry cs ( E = -538.027155015 A.U. )
C 1.309538928 1.048660302 0.000000000
C 0.000000000 0.759346920 0.000000000
H 1.630332304 2.102388803 0.000000000
H 2.083175437 0.265507033 0.000000000
H -0.793639761 1.523771533 0.000000000
Cl -0.633947150 -0.867041806 0.000000000
* It is also important to understand, that atoms are never hybridised, only orbitals are. The presence of an sp hybrid orbital does not exclude the presence of a sp3 hybrid orbital.
| {
"pile_set_name": "StackExchange"
} |
Q:
Printing linked List infinite loop C
I'm trying to print a linked list after having added a node. I have a dummy node to start the list
Node **nodeArray;
nodeArray = malloc(10 * sizeof(Node *));
int i;
for (i = 0; i < 10; i++) {
nodeArray[i] = malloc(sizeof(Node));
}
if (userChoice == 'a')
add(&nodeArray, setNumber);
void add(Node ***nodeArray, int setNumber) {
char userString[5];
printf("Please enter some data: ");
scanf("%s", userString);
Node *head = *nodeArray[setNumber]; /* head pointer to first element of array (dummy) */
Node *newNode = malloc(sizeof(Node)); /* new node to be added to array */
strncpy(newNode->data, userString, sizeof(newNode->data)); /* copies string entered by the user to data field of new node */
newNode->next = NULL; /* initializes next field of new node to NULL */
Node *tmp = head; /* pointer to head of list */
while (!tmp->next) {
tmp->next = newNode; /* inserts new node into array */
tmp = newNode; /* points head to newly added node */
}
tmp = head; /* points tmp back to head of list */
printf("List is: ");
while (tmp->next) {
printf("%s", (tmp->data));
tmp = tmp->next;
}
}
But when I print, I get an infinite loop printing out the data field of the newly added node. Terrible with linked lists....what am I doing wrong?
A:
while (tmp->next) {
tmp->next = newNode; /* inserts new node into array */
tmp = newNode; /* points head to newly added node */
}
In this snippet you're losing the refrence to the next node, and just adding the newNode next to the head. For instance you have the following list:
[1]->[2]->[3]
And you want to push a new element into that list: [4], what happens when you execute your push function (the snippet above) is:
tmp = head; // tmp = [1]
while(tmp->next) {
tmp->next = newNode; // [1]->next = [4]
tmp = newNode; // tmp = [4]
}
So the next time '(tmp->next)' is evaluated it will be evaluated as: [4]->next and it will be NULL, breaking the loop. Your list will then be:
[1]->[4]
The other elements are lost because you don't have a reference pointing to them anymore, this is called a memory leak because you won't be able to free them later.
You could write your push function this way:
tmp = head;
while(tmp->next)
tmp = tmp->next;
tmp->next = newNode // Adds new node to the tail of the linked list
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript Add Class When Link is Clicked
I have these links:
<a class="active" href="#section1">Link 1</a>
<a href="#section2">Link 2</a>
When a link 2 is clicked I would like it to receive the active class and remove the class from link 1 itself so it would effectively become:
<a href="#section1">Link 1</a>
<a class="active" href="#section2">Link 2</a>
This should work both ways. Ie. whatever link is clicked gets the class and removes it from the other.
How can this be done with JavaScript/Prototype?
A:
Try this:
// initialization
var links = document.links;
for (var i=0; i<links.length; ++i) {
links[i].onclick = function() {
setActive(links, this);
};
}
function setActive(links, activeLink) {
for (var i=0; i<links.length; ++i) {
var currentLink = links[i];
if (currentLink === activeLink) {
currentLink.className += " active";
} else {
currentLink.className = currentLink.className.split(/\s+/).map(function(val) {
return val === "active" ? "" : val;
}).join(" ");
}
}
}
A:
You could write a little helper function with prototype support that removes the class from all active elements and adds it to the one that was clicked on:
function active(e) {
$$('.active').each(function(i) {
i.removeClassName('active');
});
e.addClassName('active');
};
You can than call this function from your onclick events:
<a href="#sectiona" onclick="active(this)">a</a>
<a href="#sectionb" onclick="active(this)">b</a>
<a href="#sectionc" onclick="active(this)">c</a>
| {
"pile_set_name": "StackExchange"
} |
Q:
Batch file - How to combine multiple echo statements and also reset %errorlevel% on a single line?
I am trying to get the following output from my batch file:
ERRORLEVEL has been reset from 4 to 0
... by using the following code:
@echo ERRORLEVEL has been reset from %errorlevel% to & verify>nul & @echo %errorlevel
... The problem is that 1) errorlevel does not reset to zero, and 2) I get a carriage return at the end:
ERRORLEVEL has been reset from 4 to
4
... When I separate it into individual lines, it works:
@echo Reset ERRORLEVEL
verify>nul
@echo ERRORLEVEL = %errorlevel
... The output is:
Reset ERRORLEVEL
ERRORLEVEL = 0
I am admittedly a beginner at writing batch files, but I have done a lot of trial and error, and research. I am using "verify>nul" to reset the errorlevel based on what I found when searching this site. My understanding of using @echo is that the @ symbol will suppress the command being printed. Any help would be greatly appreciated, thanks!
A:
The reason why your code does not show two different values for %ErrorLevel% is because the environment variable is substituted in the entire command line before any command is run. Only then is the command line executed. But you need the second substitution to occur after the ver command has run.
First of all, you could take advantage of delayed expansion, in which environment variables surrounded by exclamation marks are expanded only when the command is about to be run. To turn on this mode, you need to execute SETLOCAL ENABLEDELAYEDEXPANSION
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO ERRORLEVEL has been reset from !ERRORLEVEL! to & verify>nul & ECHO !ERRORLEVEL!
(By the way Delayed Expansion only appears to work in batch files, not at the command line).
Unfortunately, there is no way of preventing the new line from being shown by the ECHO command. So instead, you are forced to do each command on a single line. But fear not, you just need to save all the values you need, and do all the output on a single line.
So your code should be:
@ECHO OFF
SET OriginalErrorLevel=%ERRORLEVEL%
verify>nul
SET NewErrorLevel=%ERRORLEVEL%
ECHO ERRORLEVEL has been reset from %OriginalErrorLevel% to %NewErrorLevel%
Incidentally, don't bother prefixing every command with "@". Just use @ECHO OFF at the top of every script, and no commands will be shown unless you subsequently use ECHO ON.
| {
"pile_set_name": "StackExchange"
} |
Q:
Expected value of quotient of identically distributed random variables
What is example of two identically distributed random variables so $$\\
E\left(\frac XY\right) \neq E\left(\frac YX\right)
$$
I know they have to be dependent, but I still don't have any idea.
A:
How about $(X,Y)=(1,2)$ or $(2,3)$ or $(3,1)$ each with probability $\frac13$?
| {
"pile_set_name": "StackExchange"
} |
Q:
use cols/rows or style-width/height to specify dimensions of textarea?
what is considered best practice when specifying the dimensions of an HTML textarea? only using cols/rows (which i think are mandatory with html strict 4.01) or specifying width and height using css properties?
or even setting cols/rows for validity and then overriding the actual size using css?
A:
Please see this question: Should I size a textarea with CSS width / height or HTML cols / rows attributes?
I agree with the top answer. You use rows/cols in case CSS is not supported; if width or height are specified using CSS, they override the value derived from rows/cols.
| {
"pile_set_name": "StackExchange"
} |
Q:
I can't execute any pip commands on my mac
Collecting coremltools
Using cached coremltools-0.6.3-cp27-none-macosx_10_13_intel.whl
Requirement already satisfied: numpy>=1.6.2 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from coremltools)
Collecting protobuf>=3.1.0 (from coremltools)
Using cached protobuf-3.4.0-py2.py3-none-any.whl
Collecting six==1.10.0 (from coremltools)
Using cached six-1.10.0-py2.py3-none-any.whl
Requirement already satisfied: setuptools in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from protobuf>=3.1.0->coremltools)
Installing collected packages: six, protobuf, coremltools
Found existing installation: six 1.4.1
DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
Uninstalling six-1.4.1:
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
prefix=options.prefix_path,
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 778, in install
requirement.uninstall(auto_confirm=True)
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 754, in uninstall
paths_to_remove.remove(auto_confirm)
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_uninstall.py", line 115, in remove
renames(path, new_path)
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 267, in renames
shutil.move(old, new)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
copy2(src, real_dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
copystat(src, dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/var/folders/5z/jqsns4n92y51f42_dbxv07vh0000gn/T/pip-7YtWLb-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'
This is the error I'm getting.
I've tried various commands and this is the general error I'm getting.
This is the complete response to when I enter
pip install coremltools
on my terminal window
P.S. I'm using macOS High Sierra.
A:
Because you use pip from the system Python. Writing to the system folders, incl. system's Python, requires the root privileges. They can be achieved by using sudo:
sudo pip install coremltools
However, keep in mind, that installing the libraries into the system is not the best idea. It will be difficult to clean it up, remove the libraries. This can also break the behaviour of the system (since it depends on Python and its specific libs, and their specific versions).
Instead, creates your virtualenv, and work on your project there:
which pip
virtualenv myenv
source myenv/bin/activate
which pip
pip install coremltools
python
>>> import coremltools
This is the recommended official way of isolating your projects from the system (and the system from your projects). For more info, read the docs: https://virtualenv.pypa.io/
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot install viber on Ubuntu 14.04 and 18.04
I downloaded a Viber deb package from the official website (August 2018). But after trying to install it I get
./viber.deb: line 1: syntax error near unexpected token `newline'
./viber.deb: line 1: `!<arch>'
Tested on Ubuntu 14.04 and 18.04.
A:
Silly mistake. I tried to install the deb package simply with
./viber.deb
but the correct way is
sudo dpkg -i viber.deb
And it worked.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make a link inside a .click function inside a loop for an array work?
I'm trying to, when the tr is clicked, open a new tab with an address, that is a Google Maps address with the variables from the code in between.
I have this HTML:
<tr>
<td>
<span class="place-address">A Street, 608, City</span>
<a class="link-maps"></a>
</td>
</tr>
<tr>
<td>
<span class="place-address">A Street, 998, City</span>
<a class="link-maps"></a>
</td>
</tr>
<tr>
<td>
<span class="place-address">A Street, 226, City</span>
<a class="link-maps"></a>
</td>
</tr>
And this JavaScript, in jQuery:
var addressesArray = [];
var linkMapsArray = [];
var placeAddress = $(".place-address").each(function() {
var addresses = $(this).text();
addressesArray.push(addresses);
});
var linkMaps = $(".link-maps").each(function() {
var links = $(this);
linkMapsArray.push(links);
});
var placesAddresses = addressesArray;
$(function() {
getLocation();
});
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(openMaps, showError);
} else {
alert("Your navigator doesn't support geolocation.");
}
}
function openMaps(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
for(j = 0; j < placesAddresses.length; j++) {
var address = placesAddresses[j];
linkMapsArray[j].closest("tr").click(function() {
window.open("https://www.google.com/maps/dir/" + latitude + "," + longitude + "/" + address + "/")
});
}
}
//omitted showError function
I don't want the link-maps to appear, that's why they are empty and with a display: none in the CSS.
The result of all of this is that, no matter wich one of the tr's I click, it will always take me to the address of the last one. But when I put the following code instead of the click function, along with display: block in the CSS, it works, but only when clicking the link, but I want it to work when clicking the tr:
linkMapsArray[j].text(address);
linkMapsArray[j].attr("href", "https://www.google.com/maps/dir/" + latitude + "," + longitude + "/" + address + "/");
PS: I know that this last code doesn't open a new tab, but it is redirecting correctly.
A:
I can't quite follow what you're trying to do. This will log the text contained within the first child <span class="place-address">...</span> of a <tr> when the <tr> is clicked. From here, you'll need to construct a Google Maps link and call window.open(...) to open a new tab.
(function(){
// get all <tr> tags
document.querySelectorAll('tr').forEach(function (tr) {
// listen for click events on each <tr>
tr.addEventListener('click', function (event) {
// log the text of the .place-address span within the clicked <tr>
console.log(tr.querySelector('.place-address').innerText);
// TODO open a new tab here window.open(...)
});
});
})();
<table>
<tbody>
<tr>
<td>
<span class="place-address">A Street, 608, City</span>
</td>
</tr>
<tr>
<td>
<span class="place-address">A Street, 998, City</span>
</td>
</tr>
<tr>
<td>
<span class="place-address">A Street, 226, City</span>
</td>
</tr>
</tbody>
</table>
| {
"pile_set_name": "StackExchange"
} |
Q:
Symfony 3.3 CraueFormFlowBundle Request_stack is empty
my first question to this site is a little difficult to describe.
I am quite new to Symfony, startet with 3.2 and updated recently to 3.3.5 (not sure if relevant for the problem).
I tried to use CraueFormFlowBundle (multistep form bundle) but cannot get it to work.
The problem is that trying to access the flow results in an exception:
Error: Call to a member function getCurrentRequest() on null
Symfony\Component\Debug\Exception\ FatalErrorException
in vendor/craue/formflow-bundle/Form/FormFlow.php (line 191)
Line 191 shows: $currentRequest = $this->requestStack->getCurrentRequest();
Modifying the FormFlow.php with dump line shows that $this->requestStack is null.
I have not enough knowledge about this bundle to know where to start looking for the problem.
The flow definition is based on the location example:
namespace EngineeringBundle\Form;
use Craue\FormFlowBundle\Form\FormFlow;
use Craue\FormFlowBundle\Form\FormFlowInterface;
class SelectExaminationFlow extends FormFlow
{
/**
* {@inheritDoc}
*/
protected function loadStepsConfig()
{
dump("loadStepsConfig");
return array(
array(
'label' => 'engineering.discipline',
'form_type' => new SelectExaminationStep1Form(),
),
array(
'label' => 'engineering.date',
'form_type' => new SelectExaminationStep2Form(),
'skip' => function($estimatedCurrentStepNumber, FormFlowInterface $flow) {
return $estimatedCurrentStepNumber > 1 && !$flow->getFormData()->canHaveRegion();
},
),
array(
'label' => 'confirmation',
),
);
}
The form definition is also quite simple and works without problems:
class SelectExaminationStep1Form extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
dump("buildForm");
$builder
->add('id', HiddenType::class)
->add('discipline', EntityType::class, array(
'class' => 'EngineeringBundle:Discipline',
'choice_label' => 'disciplineName',
'label' => 'engineering.discipline.label'
)
);
}
public function getName() {
return $this->getBlockPrefix();
}
public function getBlockPrefix() {
return 'createEngineeringStep1';
}
}
services.yml:
EngineeringBundle\Form\SelectExaminationFlow:
parent: craue.form.flow
autowire: false
autoconfigure: false
public: true
engineering.form_flow:
alias: EngineeringBundle\Form\SelectExaminationFlow
public: true
Controller:
/**
* @Route("create", name="engineering_create")
*/
public function createAction()
{
return $this->processFlow(new ExaminationDate(), $this->get('engineering.form_flow'));
}
Thanks in advance
Sebastian
A:
I was having the same problem, resolved it by adding a constructor to vendor/craue/formflow-bundle/Form/FormFlow.php with the following content:
public function __construct(RequestStack $requestStack, FormFactoryInterface $formFactory, DataManagerInterface $dataManager, EventDispatcherInterface $eventDispatcher) {
$this->formFactory = $formFactory;
$this->requestStack = $requestStack;
$this->dataManager = $dataManager;
$this->eventDispatcher = $eventDispatcher;
}
Make sure to place it after all setter-methods. Problem seems to be related to a symfony update.
| {
"pile_set_name": "StackExchange"
} |
Q:
Returning a ResponseEntity Object with different type of body using the lambda expression
Is it possible to return a ResponseEntity Object with different type of a body using the lambdas expression?
In the code below i have got of course a bad return type.
competenceRepository.findByNameIgnoreCase(postCompetenceDTO.getName()).map(competence -> {
return new ResponseEntity<String>("Competence already exist!", HttpStatus.CONFLICT);
}).orElseGet(() -> {
Competence competence = new Competence();
competence.setName(postCompetenceDTO.getName());
return new ResponseEntity<CompetenceDTO>(competence.convertToCompetenceDTO(),HttpStatus.OK);
});
Regards,
Thank you in advance
A:
Yes it's possible, you need to specify Object in your ResponseEntity, so you can put anything in it. Also you can get rude from excessive braces.
competenceRepository.findByNameIgnoreCase(postCompetenceDTO.getName())
.map(c -> new ResponseEntity<Object>("Competence already exist!", HttpStatus.CONFLICT))
.orElseGet(() -> {
Competence competence = new Competence();
competence.setName(postCompetenceDTO.getName());
return new ResponseEntity<Object>(competence.convertToCompetenceDTO(), HttpStatus.OK);
});
Hope it helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Dapper : Custom Map column to nested object
I want to map a column value to nested object.
for example in my database table i have:
Users
(
varchar UserName,
varchar Password,
binary Permitions
)
in my code i have:
User{string UserName, string Password, Permition Permitions: {...}}
I want to do something like
db.Query<User>("Select UserName, Password, Permisions PermitionsFromTable
from Users WHERE UserName=@User AND Password =@Password", new { user,
password
}, user =>
{
user.Permitions = new Permition();
user.Permitions.LoadPermitions("PermitionsFromTable");
return user ;
});
it's possible?
A:
There's an overload of Query that lets you specify more than one type to map to and a result type and you can tell it the column to split on, then you can combine the types. So, something like this should work for what you want.
db.Query<User, byte[], User>(
queryString,
new { user, password },
splitOn: "PermisionsFromTable",
(user, perm) =>
{
user.Permitions = new Permition();
user.Permitions.LoadPermitions(perm);
return user;
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Tense agreement in the past irrealis conditionals
The following is taken from PEU1 123.5:
Could have + past participle can refer to present situations which were
possible but have not been realised.
He could have been Prime Minister now if he hadn't decided to leave politics.
We could have spent today at the seaside, but we thought it was going to
rain, so we decided not to.
The above two are the examples of past irrealis conditionals.
But I just don't understand why "now" / "today" agree with the past tense (could have been Prime Minister now / could have spent today).
I would think they should be like this:
He could be Prime Minister now if he hadn't decided to leave politics.
We could spend / be spending today at the seaside, but we thought it was going to
rain, so we decided not to.
Do these two alternatives make sense? How do they differ from the original ones?
Edit:
Interestingly, as @Fantasier suggested, PEU 259.3 also introduced a similar usage:
We sometimes use structures with would have ... to talk about present and future situations which are no longer possible because of the way things have turned out.
It would have been nice to go to Australia this winter, but
there's no way we can do it. (OR It would be nice ...)
If my mother hadn't knocked my father off his bicycle thirty years ago, I wouldn't have been here now. (OR ... I wouldn't be here now.)
But PEU failed to provide more explanations about why this is acceptable and how native speakers think of and use it.
1. PEU = Michael Swan's, Practical English Usage.
A:
As Geoffrey Leech (Leech 2004) puts it, “Past hypothetical meaning and the use of the modals is one of the most difficult areas of English not only for non-native speakers, but also for native speakers” (p. 127).
I have always thought that the oversimplified rules of conditional use, so common in old-style textbooks and no longer used in linguistics, should have been abandoned long ago. Your question is a case in point. Obviously, traditional rules cannot explain such sentences.
It is much better to think of (what is commonly referred to as) conditionals type 2 as unlikely (Huddleston’s remote) and conditionals type 3 as impossible (Huddleston’s doubly remote), without any reference to present, past, or future.
Trying to keep both analyses, Leech 2004 somewhat struggles and argues that “[t]here seems to be a growing tendency, in fact, to associate the Perfect after a secondary modal purely with ‘contrary to fact’ meaning, rather than past time” (p. 128).
He also observes that in such sentences, when modals are followed by perfect auxiliaries (in the main clause), “the past meaning of the Perfect seems to have been lost” and only the ‘contrary to fact’ meaning is applicable.
Mittwoch, Huddleston, and Collins 2002 - more linguistically oriented - offer a much better analysis (see Chapter 8 in The Cambridge Grammar of the English Language). They call such constructions doubly remote (conditional) constructions. They give the following examples:
[48] i. If you had told me you were busy I would have come tomorrow.
ii. If you had come tomorrow you would have seen the carnival.
iii. If your father had been alive today he would have been distraught to see his business disintegrating like this.
They argue that the perfect auxiliaries express modal rather than temporal meaning (p. 754). Huddleston 2002 (Chapter 3 in the same grammar) adds that the difference between remote and doubly remote constructions is "not very tangible," cf. his examples below
[6] i b. If they were alive now they would be horrified.
c. If they had been alive now they would have been horrified.
To conclude, Huddleston also argues that doubly remote constructions are "fairly rare" (p. 150).
A:
As a native speaker, this 'single point in time' thing mentioned in the other answers doesn't make much sense to me.
Instead, to start with, the words 'today' and 'now' don't really have anything to do with it; 'now' doesn't add much to the first sentence: it is perfectly grammatical without it (though with a slight difference in meaning), and the same grammatical rules apply without it. 'Today' is only required in the second sentence because of mere coincidence: in this meaning, the verb 'spend' requires an adverb of time to complete it. But that's only because the verb 'spend' was chosen.
Here's a clearer example:
We could have hiked the trail, but we thought it was going to rain, so we decided not to go.
Here are the two alternatives based on your suggestions:
We could be hiking the trail, but we thought it was going to rain, so we decided not to go.*
We could hike the trail, but we thought it was going to rain, so we decided not to go.*
Neither of these sentences are natural English.
I think the best way to think of what is going on is that this kind of sentence describes a 'lost opportunity'. And in describing this kind of 'lost opportunity' English only allows past conditionals, even if that fact has consequences for today or for the future. You can think of it as "the opportunity is over and has moved into the past."
Compare the following:
You could have been rich if you hadn't wasted your youth.
The sentence is like saying 'you haven't been rich in the past, you aren't rich now, and you won't be in the future, because of what you've done in the past.'
Similarly:
If only I had bought that lottery ticket! I could have been rich!
= I had the opportunity to be rich...I don't have it any longer.
Here's an even simpler example. When you're stopped to turn at an intersection, and fail to do so even when you have the opportunity (because you're overanxious about oncoming traffic), you might afterwards say
I could have gone!
I could go/I could be going would be completely incorrect for this kind of "lost opportunity."
| {
"pile_set_name": "StackExchange"
} |
Q:
Images not found when testing website on mobile
I am attempting to test a website created in Dreamweaver on my phone. I have a copy of the folder with all the html/images in my Dropbox. Let's say that filename is "website". Inside of "website" I have a folder called "images" with all the images for the site, as well as my stylesheet.
My html files link to images like this: src="images/pic1.png"
A couple of the images are in the CSS, and are referenced like this: url(images/pic2.png)
On my computer, this works and all the images show up. On my phone in a folder that is an EXACT COPY, all of the images are broken links.
Anybody know what could be causing this?
Thank you!
A:
I think that the problem is that your Dropbox is on your computer, and not on your phone. Based on what you said, you are accessing the images locally, therefore the phone doesn't see files on your computer. Try transporting all images from Dropbox to the server where you host your website. Then the phone should be able to see the images.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I use HTTPS to pass a symmetric key used for encrypting TCP packets?
I am making a multiplayer game for fun and wish to keep it secure. The client is written in C# and the server in node.js with a working connection over TCP at the moment. I am new to this subject, and implementing something with RSA or Diffie-Hellman or TLS seems confusing and something that I could easily mess up. I have looked into using TLS, but have no idea how to do it without using a client certificate. Google is no help because it does not do well with negative searches if that makes sense; I only seem to get results for using client certificates in TLS. And so I came up with the idea of using HTTPS as a Diffie-Hellman substitute, connecting to the server using a self signed certificate (for clarification, the server is the one using the cert, english is weird), validating user login info, and passing back a key to use for symmetric encryption for the TCP packet transfers.
The general process would go like this:
1. Client initializes TCP connection with server and sends server a temporary ID.
2. Server marks the socket the user is connecting to with the temporary ID.
3. Client sends HTTPS post to server with login info and the temporary ID.
4. Server hashes/salts password and compares to database. On successful validation give authorization to the socket with the temporary ID what the validated user has access to. If either auth validation fails or no socket is found matching the temporary ID, return an error to the client(400). On success, generate a key to use for symmetric encryption and return it to the client(200).
5. The client recieves the symmetric key, and both client and server use it to talk in future communications.
The temporary ID serves the purpose of allowing the server to be able to tell which TCP socket connection to authorize when the HTTPS validates the login info. I think this would be ok against man in the middle attacks because the man would only get the temporary ID which is not used for anything else, and if it were changed the server would not find a socket with a matching ID during the HTTPS phase, and it would just return an error.
I think that this would be inferior to TLS because there will not be any packet signing going on in step 5 and future TCP communications, but it might be fine.
From what I understand about encryption, symmetric keys only act as a sort of cipher, so it probably is not too much overhead to deal with on server side.
Is this system viable?
A:
HTTPS is TLS. Using HTTPS you already establish a symmetric key as part of setting up the TLS connection. You don't need to pass yet another symmetric key around in most scenarios. You definitely should not be dealing with RSA or Diffie-Hellman directly. Just use a well-established crypto library supporting TLS/HTTPS connections. The only thing you need to consider RSA or DH or anything else is in setting up the configuration or calling parameters for your chosen library.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's your explanation of the Raven Paradox?
The Raven Paradox starts with the following statement
(1) All ravens are black.
which is equivalent to the following statement
(2) Everything that is not black is not a raven.
In all the circumstances where statement (2) is true, (1) is also true. And, if (2) is false, i.e., if we find an evidence against it, then (1) will also be false.
Now, whenever we see a Black Raven, we see an evidence which supports the statement 'All Ravens are Black'. So, if we see more and more black Raven, then our belief gets stronger and stronger that all Ravens are black.
But since the statements (1) and (2) are equivalent, so collecting evidence supporting statement (2) is also an evidence that all Ravens are black. So, if we see , for example, a red apple, then it's an evidence supporting that 'All Ravens are Black'. It's because 'A red apple' is neither black (because it is red) nor is it a Raven (because it's an Apple. Apples can't be Ravens, can they?).
This conclusion seems paradoxical, because it implies that information has been gained about ravens by looking at an apple. Also, the evidence is completely unrelated. I attempted to explain it but I'm not completely convinced by my explanation.
How can we resolve this paradox?
EDIT: It can be used to collect evidence supporting completely false statements like: 'All dinosaurs are educated'. Because we've seen plenty of things until now which are neither educated nor they're dinosaurs.
EDIT2: I think that the paradox still remains. If we have a journey and took a look at every non-black thing in the universe and found it to be non-Raven, then from this argument it should be proved that all Ravens are black. But that's paradoxical because it would mean false statements can also be proved by taking a look at everything else.
A:
If you wanted to prove all ravens are black, you could try to find all the ravens in the world and check they are black. Or you could try to find all the non-black things in the world, and check that they're not ravens. I don't recommend either of these approaches, especially the second.
There are approximately 16 million ravens in the world (source: International Union for Conservation of Nature), so if you see a black raven, you've got a very tiny bit of evidence for your hypothesis: you're about $6.25\times 10^{-8}$ of the way to a full proof.
There are about 10 quintillion insects in the world (source: Smithsonian). There are a lot of things in the world that are not insects (source: I really should tidy my desk). Let's say, conservatively, that there are 20 quintillion things in total. About 79% of them aren't black (source: DuPont; they were only counting cars, but I'm going to assume that's a representative sample). So if you saw one non-black thing that wasn't a raven, that gives you a really really tiny bit of evidence for your hypothesis - you're about $2.5\times 10^{-16}$ of the way to a proof, i.e. 1 red apple $\approx$ 4 nanoRavens.
A:
First things first. From a mathematical point of view, statements (1) and (2) are clearly equivalent and that's all there is to it.
All the rest of the "argument" is completely heuristical. When I say "heuristical" I mean the words/concepts:
"evidence"
"supports a statement"
"belief"
"collecting evidence supporting statement (2) is also evidence supporting statement (1)"
which are used terribly imprecisely and happily lead to the disguised "paradox".
If you care to define mathematically the words listed above, then a mathematical discussion is possible where we may or may not reach the conclusion that there is a paradox here. Such a chain of "arguments" leads to no paradox at all, at least not a mathematical one. A good example of a true mathematical paradox is Russel's famous paradox, whose conclusion lies well within mathematical definitions, and so finally forces us to abandon the notion of a universal set of all sets being a set. This however, is nowhere close, and hardly provides any interesting insights into mathematics.
A:
An intuitive explanation of why evidence for the second statement carries less weight is that there are far more not black things than ravens.
Suppose that you are sampling marbles from a bag. Suppose that you draw 5 and they are all black; what is the probability that all in the bag are black? You need to know how many are in the bag. Try 10, 100, 1000, etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
pip Installing a python module in Python 3, but that module has a dependency package that requires Python 2
so I am new to Python and what is a good way to learn it is to do some personal project :) So I am on my Windows and using virtualenv to contain environment
So, I need to use the Scrappy module:
pip install scrappy
Collecting scrappy
Using cached Scrappy-0.3.0.alpha.4.tar.gz
Collecting guessit (from scrappy)
Using cached guessit-2.1.4.tar.gz
Collecting tvdb_api (from scrappy)
Using cached tvdb_api-2.0.tar.gz
Collecting hachoir-metadata (from scrappy)
Using cached hachoir-metadata-1.3.3.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\USERPH\AppData\Local\Temp\pip-build-__zp7zbj\hachoir-metadata\setup.py", line 65
except OSError, err:
^
SyntaxError: invalid syntax
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\USERPH\AppData\Local\Temp\pip-build-__zp7zbj\h
achoir-metadata\
Its because hachoir-metadata is a Python2 dependent package, so I tried installing their Python 3 version
pip install hachoir3
I confirmed that it was installed using
pip list | Select-String hachoir3
so I tried running
pip install scrappy again
but same error.
Any work around to install scrappy? I cannot go down to Python 2.
Thanks!
A:
Scrappy itself contains code that only works in Python 2. I.e. Scrappy cannot be used with Python 3+.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to test jQuery Mobile changePage with Selenium WebDriver
I want to test with Selenium WebDriver a jQuery Mobile web site with some changePage() statements. If I record the actions with the Selenium IDE and play it, it works fine. But if I do the same actions with WebDriver the changePage() seems to be ignored.
Let me describe it by this small example. Let's assume I have a page like in
http://jsfiddle.net/shanabus/YjsPD/
in which a button with id "changePageButton" shall move to another page.
So, for testing with WebDriver I use this code:
driver.findElement(By.id("changePageButton")).click();
But the page does not change, instead the simulated click only seems to reload the page. Has anybody tested changePages successfully with WebDriver or an idea?
Regards
A:
I assume you have exported the test case form Selenium IDE. In this case Selenium produced a method like:
@Test
public void test() throws Exception {
driver.get(baseUrl + "/test.html");
}
But the baseUrl is ended with a slash, and test.html starts with a slash, so there are two slashes in the complete URL. In the jqueryMobile code there is a condition check in the method isEmbeddedPage() that compares web hash addresses and finds a difference and goes back to the global page instead of changing to the page2. That's why almost everything works but not the changePage due to this special check.
So if you remove the slash before test.html it should work.
I suppose this is an error in the export functionality of Selenium.
Regards!
| {
"pile_set_name": "StackExchange"
} |
Q:
SoapUI: Error getting response
I'm learning all about the SOAP api (working through the Trailhead module) and I'm having issues with SoapUI.
I'm able to make a login call successfully (username, password and token removed):
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com">
<soapenv:Header>
</soapenv:Header>
<soapenv:Body>
<urn:login>
<urn:username>[email protected]</urn:username>
<urn:password>passwordAndSecurityToken</urn:password>
</urn:login>
</soapenv:Body>
</soapenv:Envelope>
But when I try and create a record according to the instructions on the trailhead module, I get "Connection Refused" error.
Here's the call that I'm trying to execute in SoapUI (session token removed):
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com" xmlns:urn1="urn:sobject.enterprise.soap.sforce.com">
<soapenv:Header>
<urn:SessionHeader>
<urn:sessionId>mySecurityTokenHere</urn:sessionId>
</urn:SessionHeader>
</soapenv:Header>
<soapenv:Body>
<urn:create>
<!--Zero or more repetitions:-->
<urn:sObjects xsi:type="urn1:Account" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!--Zero or more repetitions:-->
<Name>Sample SOAP Account</Name>
</urn:sObjects>
</urn:create>
</soapenv:Body>
</soapenv:Envelope>
And here's the error message I'm getting:
Things I've tried:
adding my IP address to the network whitelist
following the instructions here to ensure that I'm not trying to log in using TLS1.0 (though the login call works fine so this was likely a red-herring-hail-mary flail)
Disabling my Bitdefender firewall, and ensuring that my proxy was not running.
regenerating my security token, log in with it fresh and immediately copy-paste the session ID, just in case it had expired (another long shot)
going to the location described in this post to try and find more information about the error - the file location doesn't exist on my PC.
Unfortunately my error message hasn't changed.
Any advice gratefully received. Even if someone can point me in the direction for finding a more detailed debug log in SoapUI, that would be amazing.
Edited for additional screenshots:
Here's what my login call looks like, complete with the endpoint:
And the create call that's failing:
A:
I suspect problem is the endpoint URL. It appears you are using the Enterprise API based on the structure of the urn:sObjects xsi:type.
For the partner API I'm using the following. Note that this is what comes back in the loginResponse serverUrl:
https://curious-raccoon-253753-dev-ed.my.salesforce.com/services/Soap/u/36.0/00D7F0000000001
For the enterprise API you would need to swap out the /u/ for /c/. E.g.
https://curious-raccoon-253753-dev-ed.my.salesforce.com/services/Soap/c/36.0/00D7F000000001
Of course, your trailhead playground will have a different sub domain and trailling org id
I tried again to replicate your call to the Enterprise API via SOAP UI by copy an pasting your sample request and changing the sessionId. I tried both with and without the Org ID on the end of the URL. Works on my machine™
Does SOAP UI work against other orgs, or is it just your scratch org that is causing the connection refused error?
It really seems like a networking level error. I'd try using Soap UI from a different machine and/or another tool that uses the Soap API to update records. If your sole goal is to pass the Trailhead challenge you can probably trick the validation by using another API based tool to create the Account record.
| {
"pile_set_name": "StackExchange"
} |
Q:
Variable search hint
In my searchable.xml in my android project, I get to specify a hint that appears in the edittext, when no text is written. Is there any way to dynamically set this?
In my action, I have two search buttons, that are calling startSearch passing their own parameters. I would like to set hints that reflect the selected action, based on which button was clicked - say "search movie titles", "search actors".
The way I see it, this could potentially be achievable by passing parameters to startSearch, or using a localization approach, just as I could place one hint in values-fr\strings.xml, there might be an alternative search resource file to target for when another button has been clicked? Or if the searchable.xml could be made into a selector, so that I could have it act differently in different states, somehow, that would also be fine... Problem is I haven't been able to find a means of achieving any of these.
The real reason I want to be doing this, is because the way I see it, it's the best way of communicating that the default action, when the device search button is pressed, is the first option, title search.
UPDATE
To avoid confusion, I'm happy with any declarative or programmatic approach of changing the hint in the EditText mSearchTextField in SearchDialog. What I'm unclear about is how to reference that EditText. The comments in the code linked to says "This is still controlled by the SearchManager ..." but I can't find any reference to how it can be controlled from the SearchManager either.
A:
AFAIK, There isn't any way you can access the EditText provided for search.
| {
"pile_set_name": "StackExchange"
} |
Q:
Django: роль атрибута в модуле
from django.db import models
class Pages(models.Model):
...
Какую роль играет атрибут models.Module при создании модуля? Он наследует какие-то нужные методы (если да, то какой например)?
A:
Модели реализуются как подклассы django.db.models.Model.
В данном случае models.Model указывает что это модель, а не просто какой то класс.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple Selection in Cocoa's NSTableView without Command Key
Is there any way to achieve multiple selection behavior in an NSTableView without requiring the user to hold down the command button while clicking? This was easy to do in a Carbon list box, by ORing in the cmdKey modifier flag, during mouse down processing, on the call to the HandleControlClick() function. I am new to Cocoa, and it is not clear to me how I can easily modify an event programmatically, or if this is the best solution.
A:
Subclass NSTableView and make your table view an instance of this subclass. In the subclass, respond to both mouseDown: and mouseUp: by creating a new mouse event based on the one you received, only with the NSCommandKeyMask flag ORed into the modifier flags, and passing the new event up to super.
However, I hope it will be obvious to your user that they can select multiple items. Also, don't break the Shift key—make sure contiguous selection still works.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting a created file permissions
I would like to know how can I set the permissions of a windows file?
Something like chmod(), instead it's a windows.
For example:
Create the file example.exe, and set its permissions in a way that only the owner
of this file can execute it.
I read that there's an ACL API for c somewhere, but I didn't quite get it.
A:
It's a lot more work than chmod!
I have taken the liberty of creating the file AFTER creating the security descriptor - it is safer. If you do things the other way around (create the file first) then there is a short time when the required access is not set.
Try this:
#include <windows.h>
#include <AclAPI.h>
#include <Lmcons.h>
int main()
{
SECURITY_DESCRIPTOR sd;
EXPLICIT_ACCESS ea[1];
PACL pDacl;
SECURITY_ATTRIBUTES sa;
TCHAR UserBuffer[UNLEN+1];
DWORD ulen = UNLEN;
GetUserName(UserBuffer, &ulen);
InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
BuildExplicitAccessWithName(&ea[0], UserBuffer, GENERIC_EXECUTE,
SET_ACCESS, NO_INHERITANCE);
SetEntriesInAcl(1, ea, NULL, &pDacl);
SetSecurityDescriptorDacl(&sd, TRUE, pDacl, FALSE);
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = FALSE;
sa.lpSecurityDescriptor = &sd;
CreateFileA("c:\\temp\\example.exe", GENERIC_EXECUTE, 0, &sa,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);
return 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Notices for ios app
I am a novice developer ios so much, do not judge.
My question is whether the framework of such notices or make them yourself?
You can please link to them?
A:
Not quite sure what you mean by "Notices."
If you mean the UI that you've shown above, you can try the YRDropdownView framework here:
https://github.com/onemightyroar/YRDropdownView
If you mean handling notifications shared throughout the app, then use NSNotificationCenter:
https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Activate PHP commands on login
Everytime I login into my centOS box. I need to run source /opt/rh/php54/enable to be able to run php commands. What do I need to do to my installation for this to work without running this command?
A:
That will depend on what the command is doing. However, you could automate it by adding this line to your ~/.profile:
source /opt/rh/php54/enable
That will run the source command each time you log in. There is probably a better way of doing this, presumably the enable script is just setting some variables that you could set directly but this should work as a workaround.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to correctly use CSS 3D Transform to create a "panoramic grid"?
So I tried to recreate this with CSS and it didn't really go as expected. It's not really responsive and looks a bit odd (I had to play around with margins and scale too much, so it really only looks kinda good on a very wide screen). Can anyone give me some hints on how to be more accurate? Here's my try on codepen.
HTML:
<div class="maps">
<div class="de_cache"></div>
<div class="de_cbble"></div>
<div class="de_dust2"></div>
<div class="de_inferno"></div>
<div class="de_mirage"></div>
<div class="de_nuke"></div>
<div class="de_overpass"></div>
<div class="de_train"></div>
</div>
CSS:
body, html {
margin: 50px;
padding: 0;
}
.maps {
display: flex;
}
.maps > div {
width: 100%;
height: 500px;
transform-origin: center center 0px;
transition: all 0.2s ease 0s;
-webkit-transform-origin: center center 0px;
-webkit-transition: all 0.2s ease 0s;
}
.maps > div:nth-child(1) {
margin-right: 15px;
transform: matrix3d(1, 0, 0.00, 0.00025, 0.00, 1, 0.00, 0, 0, 0, 1, 0, 0, 0, 0, 1);
background-color: lightseagreen;
}
.maps > div:nth-child(2) {
margin-right: 5px;
transform: matrix3d(0.95, 0, 0.00, 0.0002, 0.00, 0.95, 0.00, 0, 0, 0, 1, 0, 0, 0, 0, 1);
background-color: lightsalmon;
}
.maps > div:nth-child(3) {
transform: matrix3d(0.91, 0, 0.00, 0.00015, 0.00, 0.91, 0.00, 0, 0, 0, 1, 0, 0, 0, 0, 1);
background-color: palegreen;
}
.maps > div:nth-child(4) {
transform: matrix3d(0.885, 0, 0.00, 0.0001, 0.00, 0.885, 0.00, 0, 0, 0, 1, 0, 0, 0, 0, 1);
background-color: teal;
}
.maps > div:nth-child(5) {
transform: matrix3d(-0.885, 0, 0.00, 0.0001, 0.00, -0.885, 0.00, 0, 0, 0, 1, 0, 0, 0, 0, 1);
background-color: rebeccapurple;
}
.maps > div:nth-child(6) {
transform: matrix3d(-0.91, 0, 0.00, 0.00015, 0.00, -0.91, 0.00, 0, 0, 0, 1, 0, 0, 0, 0, 1);
background-color: lightpink;
}
.maps > div:nth-child(7) {
margin-left: 5px;
transform: matrix3d(-0.95, 0, 0.00, 0.0002, 0.00, -0.95, 0.00, 0, 0, 0, 1, 0, 0, 0, 0, 1);
background-color: limegreen;
}
.maps > div:nth-child(8) {
margin-left: 15px;
transform: matrix3d(-1, 0, 0.00, 0.00025, 0.00, -1, 0.00, 0, 0, 0, 1, 0, 0, 0, 0, 1);
background-color: palegoldenrod;
}
A:
Change your first layout, and set all the children centered in the middle of maps.
Now, set perspective on the container, a transform origin in some point in front of the plane, and make the items rotate.
You can adjust the amount of curvature of this effect changing the transform origin and/or the perspective position
body, html {
margin: 10px;
padding: 0;
height: 100%;
}
.maps {
border: solid 1px red;
width: 100%;
height: 100%;
perspective: 40vw;
}
.maps > div {
height: 90%;
width: 10%;
position: absolute;
left: 45%;
transform-origin: center center 280vw;
}
.maps > div:nth-child(1) {
background-color: lightseagreen;
transform: rotateY(7.7deg);
}
.maps > div:nth-child(2) {
background-color: lightsalmon;
transform: rotateY(5.5deg);
}
.maps > div:nth-child(3) {
transform: rotateY(3.3deg);
background-color: palegreen;
}
.maps > div:nth-child(4) {
transform: rotateY(1.1deg);
background-color: teal;
}
.maps > div:nth-child(5) {
transform: rotateY(-1.1deg);
background-color: rebeccapurple;
}
.maps > div:nth-child(6) {
transform: rotateY(-3.3deg);
background-color: lightpink;
}
.maps > div:nth-child(7) {
transform: rotateY(-5.5deg);
background-color: limegreen;
}
.maps > div:nth-child(8) {
transform: rotateY(-7.7deg);
background-color: palegoldenrod;
}
<div class="maps">
<div class="de_cache"></div>
<div class="de_cbble"></div>
<div class="de_dust2"></div>
<div class="de_inferno"></div>
<div class="de_mirage"></div>
<div class="de_nuke"></div>
<div class="de_overpass"></div>
<div class="de_train"></div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery validate plugin working only on last shown div
I am trying to validate my form that is a jQuery show/hide form. jQuery validate plugin only validates my last input on the last div (input type file). I can currently upload an image and submit the form successfully with the remaining inputs empty.
Below is the third div and when i click post ad with no inputs filled in, "This field is required" is shown.
Below is the first div with no validation messages
Below is the second div with no validation messages
Here is my form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Zootopia</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
</head>
<body>
<form id="ad_form" method="post">
<div id="ad_form_section1">
<div class="form-group">
<label for="ad_title">Ad Title</label>
<input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title" required>
</div>
<div class="form-group">
<label for="description">Describe what you're offering</label>
<textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
</div>
<button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section2">
<div class="form-group">
<label for="location"> Location</label>
<input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
</div>
<button type="button" id="back_section1" class="btn btn-primary"> Back </button>
<button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section3">
<div>
<label> Select pet pictures</label>
<input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
</div>
<button type="button" id="back_section2" class="btn btn-primary"> Back </button>
<input type="hidden" name="action_type" value="add" />
<input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
</div>
</form>
Here is my JavaScript:
$(document).ready(function(){
$("#ad_section2").click(function(){
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
});
$("#back_section1").click(function(){
$("#ad_form_section1").show();
$("#ad_form_section2").hide();
});
$("#ad_section3").click(function(){
$("#ad_form_section3").show();
$("#ad_form_section2").hide();
});
$("#back_section2").click(function(){
$("#ad_form_section2").show();
$("#ad_form_section3").hide();
});
$("#ad_form").validate({
rules:{
ad_title:{
required: true
},
description:{
required: true
},
location:{
required: true
}
},
messages:{
ad_title: {
required: "please enter an ad title"
},
description: {
required: "please enter a description"
},
location: {
required: "please enter a location"
}
},
submitHandler: function(form) {
var petID = $( "#pet_ad option:selected" ).val();
var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;
$(form).ajaxSubmit({
url:addAdUrl,
type:"post",
datatype: 'json',
success: function(result){
if(result.petAd == false){
alert("Pet ad already exists!");
}else{
alert("Ad posted!");
$('#image_table').hide();
}
},
error: function(error) {
alert("Error");
}
});
}
});
})
Here is my CSS:
#ad_form_section2,
#ad_form_section3{
display: none;
}
A:
You need to add a condition before you show/hide next fields
if ( $('field-id').valid() ) {
// Code
}
For example:
$("#ad_section2").click(function(){
if ($('#ad_title').valid() && $('#description').valid()) {
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
}
});
Also, don't forget to set character encoding to avoid characters range error, Add the following code just below <head> tag:
<meta charset="UTF-8">
Form Example:
$(document).ready(function(){
$("#ad_form").validate({
rules:{
ad_title:{
required: true,
minlength: 3, // set minimum title length
},
description:{
required: true,
minlength: 10,
},
location:{
required: true
}
},
messages:{
ad_title: {
required: "please enter an ad title",
minlength: "Your title must be more than 3 characters!",
},
description: {
required: "please enter a description",
minlength: "Your description must be at least 10 characters long",
},
location: {
required: "please enter a location"
}
},
submitHandler: function(form) {
var petID = $( "#pet_ad option:selected" ).val();
var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;
$(form).ajaxSubmit({
url:addAdUrl,
type:"post",
datatype: 'json',
success: function(result){
if(result.petAd == false){
alert("Pet ad already exists!");
}else{
alert("Ad posted!");
$('#image_table').hide();
}
},
error: function(error) {
alert("Error");
}
});
}
});
$("#ad_section2").click(function(){
// Check if valid before show/hide
if ($('#ad_title').valid() && $('#description').valid()) {
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
}
});
$("#back_section1").click(function(){
$("#ad_form_section1").show();
$("#ad_form_section2").hide();
});
$("#ad_section3").click(function(){
// Check if valid before show/hide
if ($('#location_ad').valid()) {
$("#ad_form_section3").show();
$("#ad_form_section2").hide();
}
});
$("#back_section2").click(function(){
$("#ad_form_section2").show();
$("#ad_form_section3").hide();
});
});
#ad_form_section2,
#ad_form_section3 {
display: none;
}
label.error {
color: red;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<div class="container">
<form id="ad_form" method="post">
<div id="ad_form_section1">
<div class="form-group">
<label for="ad_title">Ad Title</label>
<input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title">
</div>
<div class="form-group">
<label for="description">Describe what you're offering</label>
<textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
</div>
<button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section2">
<div class="form-group">
<label for="location"> Location</label>
<input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
</div>
<button type="button" id="back_section1" class="btn btn-primary"> Back </button>
<button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section3">
<div>
<label> Select pet pictures</label>
<input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
</div>
<button type="button" id="back_section2" class="btn btn-primary"> Back </button>
<input type="hidden" name="action_type" value="add" />
<input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
</div>
</form>
</div>
More examples from documentation
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the possibility of claiming tricks prevent the defense from profitting from declarer's errors?
Suppose, the declarer claims 12 tricks in a slam, but you have the opinion that
declarer can make a mistake.
Can you demand declarer to play it out, or does the tournament director decide
how many tricks declarer can claim ?
If the last answer is right, does this not prevent the defense from profitting
from declarer's errors ?
A:
Your question displays a gross misunderstanding of the capabilities of good players, even those merely the best in their club. At the club in Kingston where I mastered the game, the top 10 or 12 players could all remember the location of every significant card, for all 26 hands of a session, even several hours after a game. Once or twice a year the Director would be called in the auction of the first or second round with "This hand hasn't been shuffled since last week.", followed by an outline of where all the cards were in all four hands, and what contracts could and couldn't be made by both sides.
Also, a sound claim must cover all possible lies of the cards that remain possible given the knowledge available when the claim is made. It is for this reason that claims are only rarely made when trumps are outstanding. However it is not at all unusual for expert players to claim and concede even endplays such as Throw-ins and Simple and Double Squeezes. At this caliber of play, those techniques are common place, and thoroughly understood by all parties. By the time the hands are well enough known for a sound claim to be made, there are no mistakes left to be made in the hand by any competent, never mind expert, player; any to be made are already history.
A:
See The Laws Of Bridge (pdf), specifically Laws 68-71.
If a claim is doubted by any player (including dummy) the Director must be summoned. It's worth noting that:
A claim should be accompanied at once by a clear statement as to the order
in which cards will be played, of the line of play or defence through which
the claimer proposes to win the tricks claimed.
and:
The Director shall not accept from claimer any successful line of play
not embraced in the original clarification statement if there is an
alternative normal line of play that would be less successful.
“normal” includes play that would be careless or inferior for the class of player involved
So the rules would preclude a claimer from gaining an advantage by claiming.
| {
"pile_set_name": "StackExchange"
} |
Q:
Complex Join using criteria builder
I have the following code, where Class has a relationship with Student through students property.
Root<SchoolClass> root = criteria.from(SchoolClass.class);
Join<SchoolClass, Student> classStudentMapping = root.join("students");
This is working fine, no problem. But now I want to join to another entity which has no relationship with Classes but only with student. say Address... How I can join using criteria builder?
A:
Simply, start the secon join from classStudentMapping:
Join<Student, Address> = classStudentMapping.join("address");
This is possible because the interface involved in this process, From<Z,X>, extends Path<X>, therefore classStudentMapping is a Path<Student>.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sending Serialized Object from java server to android client
Kindly, I am having a java server and an android mobile client, the server gets an object from database (revokedUser) and sends it to the android client.
However the client receives the object by Object input stream but blocks at the readobject phase and I don't know why
In other mean, the first UIhelper in the client code is printing a reference while the second UIhelper is not
Please need your help
Server Code
public void revokeUser(String userid){
try {
Connection conn = Config.getConnection();
PreparedStatement stat = conn.prepareStatement(sql);
stat.setString(1,userid);
stat.setInt(2, listno);
stat.setInt(3, counter);
stat.execute();
revokeUserzz(userid,listno, counter);
} catch (SQLException e) {
e.printStackTrace();
}}
private void revokeUserzz(String userid, int listno, int counter) {
RevokedUser revoke = new RevokedUser();
revoke.setuserName(userid);
revoke.setlistNumber(listno);
revoke.setcounter(counter);
try {
ServerSocket serversocket = new ServerSocket(4400);
System.out.println("listening: 8888");
Socket socket = serversocket.accept();
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(revoke);
System.out.println("UserName: " +revoke.getuserName());
System.out.println("ListNumber: " +revoke.getlistNumber());
System.out.println("Counter: " +revoke.getcounter());
serversocket.close();
socket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Client Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Socket socket;
ObjectInputStream ois = null;
try {
socket = new Socket("192.168.1.115", 4400);
ois = new ObjectInputStream(socket.getInputStream());
UIHelper.displayText(this, R.id.textView1, "Object =\n" +ois.toString());
RevokedUser revoke = (RevokedUser) ois.readObject();
UIHelper.displayText(this, R.id.textView3, "Object =\n" +revoke.getuserName().toString());
}
}
/////////////////////////////////////////////////////////////////
Serialized Code
public class RevokedUser implements Serializable {
private static final long serialVersionUID = -86055680657258429L;
private int listNumber;
private int counter;
private String userName;
public RevokedUser() {
}
public int getlistNumber() {
return listNumber;
}
public void setlistNumber(int listNumber) {
this.listNumber = listNumber;
}
public int getcounter() {
return counter;
}
enter code here
public void setcounter(int counter) {
this.counter = counter;
}
enter code here
public String getuserName() {
return userName;
}
public void setuserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "RevockedUser{" +
"userIds='" + userName + '\'' +
", listNumber=" + listNumber +
", counter=" + counter +
'}';
}
A:
One potential problem is the way that you are closing stuff in the server.
If you close the Socket without closing the output stream first, it is possible that the stuff you previously wrote to the stream won't get flushed ... and the client won't see it.
(I'm not convinced this is the actual problem ... but I think you should fix it anyway.)
A second problem is that your server-side and client-side is liable to leak file descriptors. The problem is that if an exception gets thrown while you have a Socket, the exception may not get closed. Do this too often, and your will run out application will run out of either file descriptors or IP port numbers.
The correct way to deal with this is to close the Socket (and ServerSocket) in a finally clause ... so that it always gets closed.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can one detect "useless" indexes?
I have a MongoDB collection with a lot of indexes.
Would it bring any benefits to delete indexes that are barely used?
Is there any way or tool which can tell me (in numbers) how often a index is used?
EDIT: I'm using version 2.6.4
EDIT2: I'm now using version 3.0.3
A:
Right, so this is how I would do it.
First you need a list of all your indexes for a certain collection (this will be done collection by collection). Let's say we are monitoring the user collection to see which indexes are useless.
So I run a db.user.getIndexes() and this results in a parsable output of JSON (you can run this via command() from the client side as well to integrate with a script).
So you now have a list of your indexes. It is merely a case of understanding which queries use which indexes. If that index is not hit at all you know it is useless.
Now, you need to run every query with explain() from that output you can judge which index is used and match it to and index gotten from getIndexes().
So here is a sample output:
> db.user.find({religion:1}).explain()
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "meetapp.user",
"indexFilterSet" : false,
"parsedQuery" : {
"religion" : {
"$eq" : 1
}
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"religion" : NumberLong(1)
},
"indexName" : "religion_1",
"isMultiKey" : false,
"direction" : "forward",
"indexBounds" : {
"religion" : [
"[1.0, 1.0]"
]
}
}
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "ip-172-30-0-35",
"port" : 27017,
"version" : "3.0.0",
"gitVersion" : "a841fd6394365954886924a35076691b4d149168"
},
"ok" : 1
}
There are a set of rules that the queryPlanner field will use and you will need to discover and write for them but this first one is simple enough.
As you can see: the winning plan (in winningPlan) is a single (could be multiple remember, this stuff you will need to code around) IXSCAN (index scan) and the key pattern for the index used is:
"keyPattern" : {
"religion" : NumberLong(1)
},
Great, now we can match that the key output of getIndexes():
{
"v" : 1,
"key" : {
"religion" : NumberLong(1)
},
"name" : "religion_1",
"ns" : "meetapp.user"
},
to tells us that the religion index is not useless and is in fact used.
Unfortunately this is the best way I can see. It used to be that MongoDB had an index stat for number of times the index was hit but it seems that data has been removed.
So you would just rinse and repeat this process for every collection you have until you have removed the indexes that are useless.
One other way of doing this, of course, is to remove all indexes and then re-add indexes as you test your queries. Though that might be bad if you do need to do this in production.
On a side note: the best way to fix this problem is to not have it at all.
I make this easier for me by using a indexing function within my active record. Once every so often I run (from PHP) something of the sort: ./yii index/rebuild which essentially goes through my active record models and detects which indexes I no longer use and have removed from my app and removes them in turn. It will, of course, create new indexes.
| {
"pile_set_name": "StackExchange"
} |
Q:
When was the convention for the indefinite integral $\int\frac{1}{x}dx$ changed?
In Europe, in the 20th century, $\int\frac{1}{x}dx$ equalled $\ln{x}+C$. (I have references from Poland for 1930-1947 and the UK for the 1960s and 1970s).
Now, if one mentions $\int\frac{1}{x}dx=\ln{x}+C$ in Mathematics Stack Exchange, one is lynched. The doctrine is now that $\int\frac{1}{x}dx=\ln|x|+C$, and any suggestion to the contrary is a crime.
I don't want to discuss the pros and cons of this alteration, but I am interested to know: who made this change, and when? Was it intentional, or just an influential textbook? Or is this less of an "old millennium/new millennium" and more of an "Old World/New World" kind of thing?
There is an argument for posting this to Maths Stack Exchange rather than here, and I will if asked; but it is a historical question and so this seems a reasonable forum for it.
A:
Mathematicians say $\int \frac{1}{x}\;dx = \log x + C$. It works even for the complex case.
Calculus instructors say $\int \frac{1}{x}\;dx = \ln|x|+C$ for some reason, but it is WRONG in the complex case. (Perhaps that "ln" in there gives us a hint that they are writing for engineers and physicists rather than mathematicians.)
So my guess is that the change came around 1950 or so, when calculus textbook writers were no longer research mathematicians first, and textbook writers later.
| {
"pile_set_name": "StackExchange"
} |
Q:
Document fields that may be not be included in responses
I'd like to see documentation on what fields may not be included in responses or, alternatively, which fields are guaranteed to be included. Currently it's a little confusing because some fields may be left out while others may be returned as an empty string or array and I don't see any clear pattern there.
A:
Returned parameters now have an optional field in the documentation (example) that indicates whether they should always be present.
For the duration of the beta at least (not going to guarantee 1.0+, there are some performance implications) we're actually enforcing this. If a response we're to somehow not have a required field set, an error will occur which will show up in our logs.
Accordingly, if "optional": false is on a returned field feel free to really assume its always there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing a value from a class to a cell
In my app I'm using the PSCollectionView to create a view similar to pinterest. Now I'm trying to pass from my class to the cell class a value in which I insert the height of the imageView I set in the cell. When I run the app, the app create a cell exactly using this height, but the imageView has no dimension.
I post here my code:
PSCollectionView controller
- (CGFloat)collectionView:(PSCollectionView *)collectionView heightForRowAtIndex:(NSInteger)index {
NSString *width = [self.arrayWithData[index] objectForKey:@"width"];
NSString *height = [self.arrayWithData[index] objectForKey:@"height"];
NSLog(@"%@ e %@", width, height);
cellHeight = [self getHeightWith:width andHeight:height];
return cellHeight;
}
- (CGFloat)getHeightWith:(NSString *)originalWidth andHeight:(NSString *)originalHeight {
float width = [originalWidth floatValue];
float height = [originalHeight floatValue];
float multiplier = height / width;
// So che la mia cella ha una dimensione massima in larghezza di 100, da questo calcolo l'altezza
return 100 * multiplier;
}
- (PSCollectionViewCell *)collectionView:(PSCollectionView *)collectionView cellForRowAtIndex:(NSInteger)index {
ProductViewCell *cell = (ProductViewCell *)[self.psView dequeueReusableViewForClass:nil];
if (!cell) {
//cell = [[ProductViewCell alloc]initWithFrame:CGRectMake(10, 70, 100, 100)];
//cell = [[ProductViewCell alloc] initWithFrame:CGRectMake(0,0,collectionView.frame.size.width/2,100)];
cell = [[ProductViewCell alloc] initWithFrame:CGRectMake(0,0,collectionView.frame.size.width/2,cellHeight + 20)];
}
cell.imageHeight = cellHeight;
cell.labelName.text = [[self.arrayWithData objectAtIndex:index]objectForKey:@"name"];
NSURL * url = [NSURL URLWithString:[[self.arrayWithData objectAtIndex:index]objectForKey:@"url"]];
[self loadImageFromWeb:url andImageView:cell.productImage];
return cell;
}
- (void) loadImageFromWeb:(NSURL *)urlImg andImageView:(UIImageView *)imageView {
//NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:urlImg];
NSString *authCredentials =@"reply:reply";
NSString *authValue = [NSString stringWithFormat:@"Basic %@",[authCredentials base64EncodedStringWithWrapWidth:0]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
UIImage *image = [[UIImage alloc] initWithData:data];
[imageView setImage:image];
[HUD hide:YES];
} else {
NSLog(@"ERRORE: %@", error);
}
}];
}
and this code:
ProductViewCell.h
#import "PSCollectionViewCell.h"
@interface ProductViewCell : PSCollectionViewCell {
float wMargin;
}
@property(nonatomic,strong)UIImageView *productImage;
@property(nonatomic,strong)UILabel *labelName;
// I use this variable to pass the height of the cell from the class who implement PSCollectionView
@property CGFloat imageHeight;
+ (CGFloat)heightForViewWithObject:(id)object inColumnWidth:(CGFloat)cloumnWidth;
@end
ProductViewCell.m
#import "ProductViewCell.h"
#define MARGIN 8.0
@implementation ProductViewCell
- (id)initWithFrame:(CGRect)frame
{
wMargin = 5.0;
self = [super initWithFrame:frame];
if (self) {
// self.productImage = [[UIImageView alloc]initWithFrame:CGRectMake(wMargin, 5, frame.size.width - (wMargin * 2), 125)];
self.productImage = [[UIImageView alloc]initWithFrame:CGRectMake(wMargin, 5, frame.size.width - (wMargin * 2), self.imageHeight)];
self.labelName = [[UILabel alloc]initWithFrame:CGRectMake(wMargin, 130, frame.size.width - (wMargin * 2), 20)];
self.labelName.font = [self.labelName.font fontWithSize:12];
self.labelName.textAlignment = NSTextAlignmentCenter;
[self addSubview:self.productImage];
[self addSubview:self.labelName];
self.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:236.0f/255.0f blue:236.0f/255.0f alpha:1.0];
self.layer.masksToBounds = YES;
self.layer.borderWidth = 1.0f;
self.layer.cornerRadius = 10.0f;
self.layer.borderColor= [[UIColor colorWithRed:207.0f/255.0f green:207.0f/255.0f blue:207.0f/255.0f alpha:1] CGColor];
[self.productImage setContentMode:UIViewContentModeScaleAspectFit];
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
@end
When I try to log the value of self.imageHeight it shows in the console a 0, but you can see that I set this data to cellHeight in the PSCollectionView controller.
How I can send the data I calculate to my cell? There's a way to do that?
A:
Finally I did it without using setter! The solution is simply to use the frame.size.height. My cell code is the following:
- (id)initWithFrame:(CGRect)frame
{
wMargin = 5.0;
self = [super initWithFrame:frame];
if (self) {
self.productImage = [[UIImageView alloc]initWithFrame:CGRectMake(wMargin, 5, frame.size.width - (wMargin * 2), frame.size.height)];
self.labelName = [[UILabel alloc]initWithFrame:CGRectMake(wMargin, frame.size.height, frame.size.width - (wMargin * 2), 20)];
self.labelName.font = [self.labelName.font fontWithSize:12];
self.labelName.textAlignment = NSTextAlignmentCenter;
[self addSubview:self.productImage];
[self addSubview:self.labelName];
self.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:236.0f/255.0f blue:236.0f/255.0f alpha:1.0];
self.layer.masksToBounds = YES;
self.layer.borderWidth = 1.0f;
self.layer.cornerRadius = 10.0f;
self.layer.borderColor= [[UIColor colorWithRed:207.0f/255.0f green:207.0f/255.0f blue:207.0f/255.0f alpha:1] CGColor];
[self.productImage setContentMode:UIViewContentModeScaleAspectFit];
}
return self;
}
I simply used the frame.size.height to define the height of my imageView and following you can see the result:
| {
"pile_set_name": "StackExchange"
} |
Q:
Validating a list of objects - unobtrusively ASP.NET MVC 3 C#
This seem like it should be easy to implement but I am finding it challenging.
I have a list of objects in my view model that need to be validated, unobtrusively.
I have looked at FluentValidation for this yet there seems to be a bug in the collections validation implementation that does not fire the unobtrusive validator. Not sure if there is a way to use Data Annotations
for a list of objects where the validation will happen unobtrusively (and server-side)
I am looking for suggestions on how to do this. Thanks
The object
public class NewClubSponsor
{
public string SponsorContactName { get; set; }
public string SponsorContactEmail { get; set; }
public string SponsorContactPhone { get; set; }
}
I declare the list of NewClubSponsor objects in my View Model
public List<NewClubSponsor> Sponsors { get; set; }
The View
<div id="addCosponsorSection">
<!-- We have at least 1 existing sponsor -->
@if (Model.Sponsors != null)
{
for (var i = 0; i < Model.Sponsors.Count; i++)
{
string sponsorDivId = "sponsorclubname" + i.ToString();
string deleteLink = "<a class=\"icon delete cosponsor\" data-attr-divid=\""+@sponsorDivId+"\" data-attr-id=" + @Model.Sponsors[i].Id + "></a>";
<div id="@sponsorDivId">
<div class="formColumn1"><label for="sponsorclubname1">Sponsor club name</label></div>
<div class="formColumn2">@Html.EditorFor(x => x.Sponsors[i].SponsorContactName)
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[i].SponsorContactName)
</div>
</div>
<div class="formColumn3">@Html.EditorFor(x => x.Sponsors[i].SponsorContactEmail)
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[i].SponsorContactEmail)
</div>
</div>
<div class="formColumn4">@Html.EditorFor(x => x.Sponsors[i].SponsorContactPhone)@(i > 0 ? Html.Raw(deleteLink) : Html.Raw(""))
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[i].SponsorContactPhone)
</div>
</div>
</div>
<div class="clear"></div>
}
}
else
{
<!-- No sponsors added yet. We need at least 1 sponsor -->
<div id="sponsorclubname1">
<div class="formColumn1"><label for="sponsorclubname1">Sponsor club name</label></div>
<div class="formColumn2">@Html.EditorFor(model => model.Sponsors[0].SponsorContactName)
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[0].SponsorContactName)
</div>
</div>
<div class="formColumn3">@Html.EditorFor(model => model.Sponsors[0].SponsorContactEmail)
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[0].SponsorContactEmail)
</div>
</div>
<div class="formColumn4">@Html.EditorFor(model => model.Sponsors[0].SponsorContactPhone)
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[0].SponsorContactPhone)
</div>
</div>
</div>
<div class="clear"></div>
<!-- END Static HTML -->
}
</div>
A:
You can add Data Annotation in the object that the list is composed of.
This will add the data-valid and requerire attributes...
But, if the list is created on the fly, you will need to bind the validation logic once you add a new item in the form (if you are adding it via JS).
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery ReplaceWith() function -- Table
I am very new to JQuery and I cannot seem to get my replaceWith() function to act how I want it to.
Goal:
Replace a button (button1) with a form table (table1). I placed button1 inside its own div within a main contentholder div (my wrapper). Table1 is hidden but also in its own div, just somewhere else on the page.
What I am trying:
$(document).ready(function(){
$("#button1").click(function(){
$("#buttondiv").replaceWith("#tablediv").show;
});
});
A:
You can use this within the click handler to refer to the clicked #button1 element. Try this:
$("#button1").click(function() {
var $table = $('#table1').show();
$(this).replaceWith($table1);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Is available OpenCL on iOS
I found this thread on the forum Are either the IPad or IPhone capable of OpenCL? but is it quite old. Also, what I can gather that OpenCL is available to system libraries of iOS but not to public. Is there more info in this regard or any update ?
A:
Even with using OpenCL as private framework, on iOS it won't give you the benefits of GPU ( or others like DSPs/FPGAs if existing ). It just gives you multiple cores available on arm processor. I ran the below code to verify the OpenCL devices accessible in iOS and OS X.
Output on iOS
ARM CPU Device
Output on OS X
Radeon HD 4670
Intel(R) Core(TM) i3 CPU 540 @ 3.07GHz
Source with error checks excluded. Using OpenCL headers available(1) and linking OpenCL from (/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/System/Library/PrivateFrameworks)
#include "OpenCL/cl.h"
#include <iostream>
cl_context_properties prop[] = { CL_CONTEXT_PLATFORM, 0, 0 };
//get num of platforms
cl_uint num;
cl_int err = clGetPlatformIDs(0, 0, &num);
//get each platform
cl_platform_id *platforms = new cl_platform_id[num];
err = clGetPlatformIDs(num, platforms, &num);
//create context for platform
prop[1] = (cl_context_properties) platforms[0];
cl_context context = clCreateContextFromType(prop, CL_DEVICE_TYPE_ALL, NULL, NULL, &err);
//get num devices
size_t numDevices=0;
clGetContextInfo(context, CL_CONTEXT_DEVICES, 0, NULL, &numDevices);
cl_device_id *devices = new cl_device_id[ numDevices ];
//get every device
clGetContextInfo(context, CL_CONTEXT_DEVICES, numDevices, devices, 0);
//get info of every device
for( int idx=0; idx < numDevices; ++idx) {
size_t bufSize=0;
clGetDeviceInfo(devices[idx], CL_DEVICE_NAME, 0, NULL, &bufSize);
if( bufSize > 0 ) {
char* devName = new char[ bufSize ];
clGetDeviceInfo(devices[idx], CL_DEVICE_NAME, bufSize, devName, 0);
std::cout << "Device Name: " << devName << '\n';
}
}
Suggestion: As of now, we will need to use either OpenGL(2) or Accelerate framework(3). Still not sure, for what reason/purpose OpenCL is copied in as private framework on iPhone.
A:
Available only through private API.
F.e. https://github.com/linusyang/opencl-test-ios
| {
"pile_set_name": "StackExchange"
} |
Q:
How to check field data is numeric when using inline Script in ElasticSearch
Per our requirement we need to find the max ID of the document before adding new document. Problem here is doc may contain string data also So had to use inline script on the elastic query to find out max id only for the document which has integer data otherwise returning 0. am using following inline script query to find max-key but not working. can you help me onthis ?.
{
"size":0,
"query":
{"bool":
{"filter":[
{"term":
{"Name":
{
"value":"Test2"
}
}}
]
}},
"aggs":{
"MaxId":{
"max":{
"field":"Key","script":{
"inline":"((doc['Key'].value).isNumber()) ? Integer.parseInt(doc['Key'].value) : 0"}}
}
}
}
A:
The error is because the max aggregation only supports numeric fields, i.e. you cannot specify a string field (i.e. Key) in a max aggregation.
Simply remove the "field":"Key" part and only keep the script part
{
"size": 0,
"query": {
"bool": {
"filter": [
{
"term": {
"Name": "Test2"
}
}
]
}
},
"aggs": {
"MaxId": {
"max": {
"script": {
"inline": "((doc['Key'].value).isNumber()) ? Integer.parseInt(doc['Key'].value) : 0"
}
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Dataframes based off the value in the last row
How can I subset a CSV in R based on the value in each column of the last row?
For example, I read in a CSV file called mnist.csv and it is of dimension 400x600.
columns 1 2 3 4 .......... 600
rows: 1
2
3
4
.
.
.
400 0 0 0 1 1 1 ...3 3 3
I want to create dataframes that will only have the column and rows where the value is 0 in the last row and another dataframe where the value is 1 in the last row
A:
Using sample data, looking instead for 4 instead of 0:
mtcars[,mtcars[nrow(mtcars),] == 4L,drop=FALSE]
Disecting that:
nrow(mtcars) allows us to index on the "last" of each column
mtcars[...,] returns a 1-D matrix, the last values of each column
... == 4L returns a logical vector, corresponding to each column that matches
mtcars[,...,drop=FALSE] just does the column-subsetting; the drop=FALSE is to guard against the matrix being simplified to a vector when only one column matches, as is the case in mtcars[,mtcars[nrow(mtcars),] == 2L].
| {
"pile_set_name": "StackExchange"
} |
Q:
When and how is collectionView:viewForSupplementaryElementOfKind:atIndexPath: called?
I'm trying to implement a native-Calendar-app-like timeline view with UICollectionView and custom layout. And I'm new to it.
Here is where my problem come from.
I'm using Decoration View to implement those background gridlines, and trying to use Supplementary View to make the time labels (near the gridlines), and will use Cell to make the events but not that far yet.
But before doing the events, I found when I run it all the supplementary views are not working, no matter if I have cell or not. And I found my collectionView:viewForSupplementaryElementOfKind:atIndexPath: method is not called.
So I'm wondering how and when this method is called? What could be leading to my situation that it's not called?
Actually, is it good to make those time labels with supplementary view? I'm not sure about it since I do need them to be visible even when there's no event (no cell/item in section).
Here is my code:
View Controller
- (void)viewDidLoad
{
[super viewDidLoad];
self.collectionView.backgroundColor = [UIColor whiteColor];
[self.collectionView registerClass:TodayCellKindTask.class forCellWithReuseIdentifier:CellKindTaskIdentifier];
[self.collectionView registerClass:TodayTimelineTimeHeader.class forSupplementaryViewOfKind:TimelineKindTimeHeader withReuseIdentifier:TimelineTimeHeaderIdentifier];
[self.timelineViewLayout registerClass:TodayTimelineTileWhole.class forDecorationViewOfKind:TimelineKindTileWholeHour];
[self.timelineViewLayout registerClass:TodayTimelineTileHalf.class forDecorationViewOfKind:TimelineKindTileHalfHour];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 5;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
TodayCellKindTask *cellTask = [collectionView dequeueReusableCellWithReuseIdentifier:CellKindTaskIdentifier forIndexPath:indexPath];
return cellTask;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
NSLog(@"viewForSupplementaryElementOfKind");
TodayTimelineTimeHeader *timeHeader = [self.collectionView dequeueReusableSupplementaryViewOfKind:TimelineKindTimeHeader withReuseIdentifier:TimelineTimeHeaderIdentifier forIndexPath:indexPath];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSDateComponents *comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:today];
[comps setHour:indexPath.item];
timeHeader.time = [calendar dateFromComponents:comps];
return timeHeader;
}
Custom Layout
// in prepareLayout
NSMutableDictionary *timeHeaderAttributes = [NSMutableDictionary dictionary];
CGSize headerSize = [TodayTimelineTimeHeader defaultSize];
CGFloat headerOffsetY = (tileSize.height - headerSize.height) / 2;
for (NSInteger hour = 24; hour >= 0; hour--) {
NSIndexPath *timeHeaderIndexPath = [NSIndexPath indexPathForItem:hour inSection:0];
UICollectionViewLayoutAttributes *currentTimeHeaderAttributes = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:TimelineKindTimeHeader withIndexPath:timeHeaderIndexPath];
CGFloat headerPosY = hour * 2 * tileSize.height + headerOffsetY;
currentTimeHeaderAttributes.frame = CGRectMake(TimeHeaderPosX, headerPosY, headerSize.width, headerSize.height);
timeHeaderAttributes[timeHeaderIndexPath] = currentTimeHeaderAttributes;
}
self.timelineTileAttributes[TimelineKindTimeHeader] = timeHeaderAttributes;
// layoutAttributesForSupplementaryViewOfKind
- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
return self.timelineTileAttributes[kind][indexPath];
}
// layoutAttributesForElementsInRect
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSMutableArray *allAttributes = [NSMutableArray arrayWithCapacity:self.timelineTileAttributes.count];
[self.timelineTileAttributes enumerateKeysAndObjectsUsingBlock:^(NSString *elementIdentifier,
NSDictionary *elementsInfo,
BOOL *stop) {
[elementsInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath,
UICollectionViewLayoutAttributes *attributes,
BOOL *stop) {
if (CGRectIntersectsRect(rect, attributes.frame)) {
[allAttributes addObject:attributes];
}
}];
}];
return allAttributes;
}
// collectionViewContentSize
- (CGSize)collectionViewContentSize {
CGSize tileSize = [TodayTimelineTileWhole defaultSize];
CGFloat contentHeight = tileSize.height * self.numberOfTiles;
return CGSizeMake(tileSize.width, contentHeight);
}
I tried not to post all the code here since that'd be a lot, but let me know if you need to know others.
Any tip is appreciated!
Pine
A:
So, this problem is solved, and the reason was my stupid mistake, setting those views' position x out of the screen, and due to that the method was not called. Nothing else.
I found this reason by logging out each view's frame in prepareLayout, and found the x position was wrong. I got this position from the retina design so…
I used supplementary view and it was working without any problem.
My lesson: no worries, calm down. This can save you time from making mistake.
| {
"pile_set_name": "StackExchange"
} |
Q:
Start html5 video within an owl.carousel
I'm building a males fashion site with a slider that have both images and a video in it. I'm using owl.carousel as a slider. The video is an plane HTML5 video tag.
I'm trying to start the video whith jquery like this: $('#video')[0].play();
It works perfectly when the video is outside the slider/carousel, but how do I start it inside?
Codepen link
A:
I just look your codepen. After few tests, I saw two containers with class video-slider with a video tag with the same id "video" inside. (Check with debug console on the render view and the jquery code $(".video-slide").children()).
You can start the videoS with the jquery code $(".video-slide").children().each(function() { this.play(); }); but before you need to find where and why your blocks are duplicated.
I hope it helps
| {
"pile_set_name": "StackExchange"
} |
Q:
Extjs show link on a single word
How can I show a link in a single word like so :
Click **here** (link only when clicking on the word here)
I manage to create a link component with Extjs like this (I'm using Extjs 4.1), but the problem is that link is on the whole phrase.
{
xtype : 'component',
autoEl: {
tag: 'a',
target: '_blank',
href: 'help/GUI_help.html',
html: 'Help on GUI.'
}
}
Any help would be appreciated.
A:
This is probably the simplest solution:
{
xtype: 'component',
html: 'Help on <a href="help/GUI_help.html" target="_blank">GUI</a>'
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Multidimensional Arrays in Objective C
I have an NSDictionary filled with data. If this was php it might be accessed by something like:
$data = $array['all_items'][0]['name'];
How do I do something similar in objective c? ($array would be an NSDictionary)
A:
The equivalent code in Objective-C is:
id data = [[[array objectForKey:@"all_items"] objectAtIndex:0] objectForKey:@"name"];
Note that objectForKey: is a method of NSDictionary, and objectAtIndex: is a method of NSArray.
A shortcut in Xcode 4.5, using LLVM 4.1, is:
id data = array[@"all_items"][0][@"name"];
Also note that if "array" is an NSDictionary instance and you want to get an array of all values in the dictionary, you use the allValues method of NSDictionary:
id data = [array allValues][0][@"name"];
Of course, allValues returns an unsorted array, so accessing the array by index is not very useful. More typically, you'd see:
for (NSDictionary* value in [array allValues])
{
id data = value[@"name"];
// do something with data
}
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.