text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Spark: Convert column of string to an array
How to convert a column that has been read as a string into a column of arrays?
i.e. convert from below schema
scala> test.printSchema
root
|-- a: long (nullable = true)
|-- b: string (nullable = true)
+---+---+
| a| b|
+---+---+
| 1|2,3|
+---+---+
| 2|4,5|
+---+---+
To:
scala> test1.printSchema
root
|-- a: long (nullable = true)
|-- b: array (nullable = true)
| |-- element: long (containsNull = true)
+---+-----+
| a| b |
+---+-----+
| 1|[2,3]|
+---+-----+
| 2|[4,5]|
+---+-----+
Please share both scala and python implementation if possible.
On a related note, how do I take care of it while reading from the file itself?
I have data with ~450 columns and few of them I want to specify in this format.
Currently I am reading in pyspark as below:
df = spark.read.format('com.databricks.spark.csv').options(
header='true', inferschema='true', delimiter='|').load(input_file)
Thanks.
A:
There are various method,
The best way to do is using split function and cast to array<long>
data.withColumn("b", split(col("b"), ",").cast("array<long>"))
You can also create simple udf to convert the values
val tolong = udf((value : String) => value.split(",").map(_.toLong))
data.withColumn("newB", tolong(data("b"))).show
Hope this helps!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Laravel 5 - Can't route to controller
I'm having an issue routing in laravel 5. My code is:
<?php
Route::get('/', function () {
return "Ok";
});
//Authentication Routes
Route::post("/authenticate", "AuthenticationController@Authenticate");
Route::post("/register", "AuthenticationController@Register");
If i place the inline functions, it all works well, however when I try the controller way, it just outputs a blank page.
Any ideas?
Edit: Here's the controller
<?php
namespace App\Http\Controllers;
use User;
use Auth;
use Input;
use Hash;
use Illuminate\Routing\Controller as BaseController;
class AuthenticationController extends BaseController
{
public function Authenticate() {
if(Auth::attempt([ 'email'=>Input::get('email'),
'password'=>Input::get('password')]))
{
return response()->json("OK");
}
else
{
return response()->json("ERROR");
}
}
public function Register() {
return response()->json("Not Implemented");
}
}
A:
You're extending the wrong Controller here:
use Illuminate\Routing\Controller as BaseController;
Also set in your .env file debug=true to see what the Error is.
Probably is controller related issue.
You should extend the Controller within your app\Http\Controllers\ folder. (which falls within the same namespace). Especially to get ValidatesRequests trait working (really useful!).
Fix your controller by removing the:
use Illuminate\Routing\Controller as BaseController;
Example:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Hash;
class AuthenticationController extends Controller
{
public function Authenticate() {
if(Auth::attempt([ 'email'=>Input::get('email'),
'password'=>Input::get('password')]))
{
return response()->json("OK");
}
else
{
return response()->json("ERROR");
}
}
public function Register() {
return response()->json("Not Implemented");
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the reason for adding registers four times as shown in the example?
I've only just begun to learn MIPS and this particular example has me confused. Particularly adding the registers four times.
Here is the example that I'm talking about:
What is the purpose of doing add $t0, $s1, $s1
and then add $t0, $t0, $t0 so that you have four times of what int k was?
A:
It's used for the conversion from the int array index (code) to the byte array index (memory).
k is the index of the int array in the code. The size of an int is 4 bytes. To load the value from the byte array in memory, you will go to the byte position k * 4. Adding happens to be the simplest operation to achieve this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
The circle of three
I'm the first, but also second
I'm rather odd, but also not
I am the circle of three
What am I?
A:
You are the
Second hand in a clock
Explanation Follows
I'm the first, but also second
Second hand is the fastest and to reach the 12 hour mark first. But its calles Second.
I'm rather odd, but also not
Some time the second hand points to an odd number but in the next instant it will be an even number
I am the circle of three
The rotation of second hand manages second, minutes (one complete rotation of second hand) and hours (60 complete rotations of second hand). The numbers/points in circular form in a clock represents seconds, minutes and hours.
A:
You are:
2
I'm the first, but also second
The first prime, but also the second (depending on convention: 1 used to be regarded as prime).
I'm rather odd, but also not
2 is the oddest prime (it is even).
The circle of three
???
A:
You are:
a clock
I'm the first, but also second
the first to show the time and the seconds in the time
I'm rather odd, but also not
the hour, minute and second can be odd numbers and also can be not odd i.e. even
The circle of three
a clock is a circle with three hands
|
{
"pile_set_name": "StackExchange"
}
|
Q:
iOS: Custom Cell Properties with Code and IB do not appear together
CustomCell.h
@interface CustomCell : UITableViewCell
//Properties created in Code, not via IB.
@property (nonatomic, strong) UILabel *labelUsername;
@property (nonatomic, strong) UIView *circle;
//Properties Created through IB by control+drag
@property (nonatomic, strong) UILabel *labelFirstName;
@property (nonatomic, strong) UILabel *labelLastName;
@end
CustomCell.m
@implementation CustomCell
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
//Creating properties in code
self.circle = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 40.0f, 40.0f)];
[self.circle setBackgroundColor:[UIColor brownColor];
self.labelUsername = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 200.0f, 50.0f)];
self.labelUsername.textColor = [UIColor blackColor];
[self.contentView addSubview:self.labelUsername];
[self.contentView addSubview:self.circle];
}
return self;
}
tableView.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *customCellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:customCellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:inviteCellIdentifier];
}
cell.labelFirstName.text = @"FirstName";
cell.labelLastName.text = @"LastName";
return cell;
}
The code above continued to show labelUsername and circle. However, the properties created using the IB (labelFirstName and labelLastName) did not appear.
So in tableView.m in viewDidLoad I registered the Nib with the following code:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView registerNib:[UINib nibWithNibName:@"CustomCell"
bundle:[NSBundle mainBundle]]
forCellReuseIdentifier:@"CustomCell"];
}
Now labelFirstName and labelLastName appear, but the properties created with code (labelUsername and circle) DO NOT appear.
How can I get all 4 properties to show?
A:
Try this in CustomCell.m,
- (void)awakeFromNib
{
[super awakeFromNib];
self.circle = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 40.0f, 40.0f)];
[self.circle setBackgroundColor:[UIColor brownColor];
self.labelUsername = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 200.0f, 50.0f)];
self.labelUsername.textColor = [UIColor blackColor];
[self.contentView addSubview:self.labelUsername];
[self.contentView addSubview:self.circle];
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
low code, simplistic Azure Website security using windows live provider?
I have this webpage I need to secure on Azure. I want to be the only person who can access it. I don't need a fancy login or error page process. The page/site was formerly running on my home web server and so windows authentication via the web.config authentication tag was "really easy" to implement.
I'm looking at Azure Authentication models with STS, ACS, SAML, Federated... and truthfully am somewhat confused about what I need to do. Also, I'm wondering why MS did not offer a simple control panel interface to secure and maintain access to websites so we don't have to create services and custom web site code to manage all of this.
At a high level, what are the minimum steps I need to perform to accomplish this?
A:
If you are the only one going to use the site, then I'm not sure you need to go through all that trouble.
But, on the other hand, doing what you want is not that complicated:
Get an ACS namespace
Install WIF in your machine
Run "Add STS Reference" in your web project and point to your ACS namespace
(look for Federation metadata endpoint)
Configure LiveID trust in ACS (or any other of the pre-provisioned IdPs)
Configure ACS to issue a token for your app
Since your needs are very simple, the default rules will probably work for you.
Here's an article that explains everything step-by-step.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to obtain human-readable mercurial push-command traffic example
I am doing push using mercurial hg to bitbucket.org using https.
There is a bunch of changes to text files and also binary files added. So I would like to capture the real traffic of this command in http format to analyze. How can I make it? Or at least inspecting an example of captured human-readable push would be great.
There is a link for mercurial wire protocol, but no example how it might really look.
A:
There are a couple of proxies (http://mitmproxy.org/ is popular, I really like http://www.charlesproxy.com/) which can MITM the HTTPS connection… However, it might be simpler to start a local Mercurial server, then sniff that connection:
$ cd some-hg-repo/
$ hg serve
… listening at http://127.0.0.1:8000/ …
Then fire up your packet sniffer watching on the loopback interface, and from another shell:
% hg clone http://127.0.0.1:8000/ repo-clone
% cd repo-clone
% fortune > foo.c
% hg commit -m "change to foo"
% hg push
And here's a bit of what it looks like:
$ sudo tcpdump -i lo0 -A 'tcp port 8000 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
03:15:05.515867 IP localhost.52031 > localhost.irdmi: Flags [P.], seq 2116430132:2116430284, ack 835526317, win 40830, options [nop,nop,TS val 269453377 ecr 269453377], length 152
E....2@.@............?.@~&)41......~.......
...A...AGET /?cmd=capabilities HTTP/1.1
Accept-Encoding: identity
host: localhost:8000
accept: application/mercurial-0.1
user-agent: mercurial/proto-1.0
… snip …
03:15:05.516780 IP localhost.irdmi > localhost.52031: Flags [P.], seq 173:303, ack 152, win 40830, options [nop,nop,TS val 269453378 ecr 269453378], length 130
E...8b@.@............@.?1..Y~&)....~.......
...B...Blookup changegroupsubset branchmap pushkey known getbundle unbundlehash batch stream unbundle=HG10GZ,HG10BZ,HG10UN httpheader=1024
GET /?cmd=batch HTTP/1.1
Accept-Encoding: identity
x-hgarg-1: cmds=heads+%3Bknown+nodes%3D
host: localhost:8000
vary: X-HgArg-1
accept: application/mercurial-0.1
user-agent: mercurial/proto-1.0
…snip…
03:15:05.528852 IP localhost.irdmi > localhost.52033: Flags [P.], seq 474:516, ack 355, win 40830, options [nop,nop,TS val 269453389 ecr 269453389], length 42
E..^.h@.@[email protected]...,.....~.R.....
...M...M92550c48fd2dc2c112ac88215eff29a5012abff1
;
03:15:05.529756 IP localhost.52033 > localhost.irdmi: Flags [P.], seq 355:628, ack 516, win 40830, options [nop,nop,TS val 269453390 ecr 269453389], length 273
E..E.N@[email protected].@.,...W.....~.9.....
...N...MGET /?cmd=getbundle HTTP/1.1
Accept-Encoding: identity
x-hgarg-1: common=0000000000000000000000000000000000000000&heads=92550c48fd2dc2c112ac88215eff29a5012abff1
host: localhost:8000
vary: X-HgArg-1
accept: application/mercurial-0.1
user-agent: mercurial/proto-1.0
…snip…
03:15:05.535163 IP localhost.irdmi > localhost.52033: Flags [P.], seq 688:6194, ack 628, win 40830, options [nop,nop,TS val 269453395 ecr 269453394], length 5506
E...AZ@.@[email protected]...,.....~.......
........]..>O..3.x....L .-.....I.mh....M}.i!..Bh8.PL. .O
1iB ...C.....4.4....:...H..w....7.\..#.{.p.......-g.....^[email protected]^19QP....l.....1.d.ukh.5..M.....k.A..<'.2..,.2.......{.q.(?.....rc"._.........m.xx.';...]V_0..e..j..{....OWf.n........J.bZ&kVXAR4...!....*[email protected];#....c.F..._.m.a|. .........=.
… snip …
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Swift 3 generics: issue with setting UICollectionViewDatasource & Delegate for a UICollectionView inside UITableViewCell
I'm in the process of translating my app to Swift 3. I stumbled upon an issue with using a clean way of setting datasource and delegate for a UICollectionView inside a UITableViewCell, described here.
The code is as follows:
func setCollectionViewDataSourceDelegate<D: protocol<UICollectionViewDataSource, UICollectionViewDelegate>>
(_ dataSourceDelegate: D, forRow row: Int) {
collectionView.delegate = dataSourceDelegate
collectionView.dataSource = dataSourceDelegate
collectionView.tag = row
collectionView.reloadData()}
And it throws a warning, stating:
'protocol<...>' composition syntax is deprecated; join the protocols using '&'
When I accept the suggested solution, it changes the D: protocol<UICollectionViewDataSource, UICollectionViewDelegate> into a D: (UICollectionViewDatasource & UICollectionViewDelegate) call, and instead throws an error:
Expected a type name or protocol composition restricting 'D'
I'd be much obliged if someone with a better understanding of Swift 3 generics than myself could suggest a solution.
A:
No need to use protocol<> because the compiler already knows that. Just join the protocols like this: D: UITableViewDelegate & UITableViewDataSource
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How accurate and precise is a dyno and why?
It was pointed out to me that if you do two back to back runs of the same car on the same dyno the graph of the results will be different. Also, if you run the exact same car on two different dynos the results will not match.
Why are the results different in each scenario?
How precise are the results obtained from a dyno (i.e. what is the margin of error)?
Note: Thanks to the tag at the bottom, I realised that a dyno is short for a dynamometer (which is defined as a device that measures horsepower and torque).
A:
Every dyno is going to read things differently. This is inherent due to several factors, which include, but are not limited to, atmospheric conditions (temp, barometric readings, etc), testing conditions (do they place a fan in front of the radiator, how tight did they tie down the vehicle, etc), type of dyno (eddy current or acceleration), or manufacturer of the dyno itself (Mustang, Dynojet, Superflow, etc.). Even the quality of the gas can have different results. Each is going to provide different readings.
It is a well known that different brands of dynos produce different results. There is a big rift in the hotrod community as to whether the Dynojet or Mustang dyno is better. Each provides a number, but they are usually different.
With a dyno there is one major thing you need to consider, that being am I being consistent? As stated, there are two major reasons to use a dyno in the first place.
First is tuning. A dyno will allow your tuner get a better than baseline tune (doing a road tune will provide a better tune as these produce real world driving conditions). Any type of dyno will work in this situation because you are only trying to get the most out of the vehicle no matter the power/torque levels.
Secondly is to observe a difference. Before you do work on a vehicle of a performance nature, it's a good habit to get into to put the vehicle on a dyno and test it out to see what are it's current power/torque levels. In doing so, you give yourself a baseline. When you do the modification, take the vehicle back to the same dyno and test it again. This will give you the difference. Why use the same dyno? Simply to allow the vehicle a fair shake and to be as accurate against the baseline run as possible. No two dyno runs are going to be completely accurate against each other. If you are using two different dynos to check your results, these numbers are going to be farther away from the truth of the gain (or decrease). You want as close as you can get and using the same dyno is about the only way to do it.
I don't have any hard and fast numbers for you as to how close is a dyno really. It mainly depends on how often the dyno is calibrated and how well that calibration is done.
One thing of note here is that most dynos take into account the atmospheric conditions encountered at the time of the dyno run. The computer will usually adjust the figures based on these and spit out an answer which is the adjusted value at mean sea level under perfect conditions. This allows the vehicle owner to have as close to standard of a number as which it can be. They can then take the number and compare it to other dyno runs and know the numbers are about as close as can be expected.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I drag and drop with multiple activities?
I used the Service call to create a Floating Window that floats over all other views/activities. This window has its own Activity and is different from Dialog.
Now i want to add a Drag&Drop action to this window, for example if you long click an ImageView in the Floating Window, you can Drag and Drop it into another Activity(or base Activity). I've been tried to use OnLongClickListener to trigger Drag event, and added OnDragListener to catch the Drop event. Here's what i have so far :
public class MyFloatableActivity extends FloatActivity {
private ImageView mImg;
private MyDragEventListener mDragListen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.float_activity));
// This imageView is for Drag&Drop test
mImg = (ImageView)findViewById(R.id.drag_img));
mImg.setOnLongClickListener(new ImageView.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
ClipData dragData = ClipData.newPlainText("dragtext", "dragtext");
v.startDrag(dragData, new View.DragShadowBuilder(v), null, 0);
return false;
}
});
mImg.setOnDragListener(mDragListen);
switchToFloat(); // Make this activity to float
}
MyDragEventListener class is :
public class MyDragEventListener implements View.OnDragListener {
private ClipData mDragData;
@Override
public boolean onDrag(View v, DragEvent event) {
final int action = event.getAction();
ImageView img;
if(v instanceof ImageView) {
img = (ImageView)v;
} else{
return false;
}
switch(action) {
case DragEvent.ACTION_DRAG_STARTED:
if(event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
Log.d("DDD", "Drag started!!!");
return true;
}else {
return false;
}
case DragEvent.ACTION_DRAG_ENTERED:
Log.d("DDD", "Entered!!!");
case DragEvent.ACTION_DRAG_LOCATION:
case DragEvent.ACTION_DRAG_EXITED:
return true;
case DragEvent.ACTION_DRAG_ENDED:
case DragEvent.ACTION_DROP:
Log.d("DDD", "Action drop!!!");
return true;
}
return true;
}
The reason i implemented OnDragListener is to listen ACTION_DROP event in base Activity when ImageView is dropped. This allows me to determine whether the ImageView was dropped on the destination image, or the layout. Here's my base Activity :
public class DragAndDropDemo extends Activity {
private ImageView mImg;
private MyDragEventListener mDragListen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drag_and_drop);
//findViewById(R.id.drag_layout).setOnDragListener(mDragListen);
mImg = (ImageView)findViewById(R.id.dest_img);
mImg.setOnDragListener(mDragListen);
}
The problem is OnDragListener in DragAndDropDemo is not being invoked, so i couldn't catch the Drop event in my base Activity. I've seen many examples of Drag and Drop, but never got to the right solution. I'm wondering if throwing a Drag&Drop event to different Activity in Android is possible. If Android could do it, what would it be?
Is there anyone can help?
A:
I found the solution by myself. I integrated OnDragListener into MyFloatableActivity, and send intent to DragAndDropDemo activity to receive intents whenever a drop event occurs.
So here's my code.
public class MyFloatableActivity extends FloatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
mImg.setOnDragListener(new View.OnDragListener() {
@Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
if (event.getClipDescription().hasMimeType(
ClipDescription.MIMETYPE_TEXT_PLAIN)) {
return true;
} else {
return false;
}
case DragEvent.ACTION_DRAG_ENTERED:
case DragEvent.ACTION_DRAG_LOCATION:
case DragEvent.ACTION_DRAG_EXITED:
return true;
case DragEvent.ACTION_DRAG_ENDED:
case DragEvent.ACTION_DROP:
Intent intent = new Intent();
intent.setAction("com.test.DragAndDrop");
intent.putExtra("Drop", 0);
sendBroadcast(intent);
return true;
}
return false;
}
});
...
}
and in DragAndDropDemo,
public class DragAndDropDemo extends Activity {
...
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("com.test.DragAndDrop");
registerReceiver(mBR, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mBR);
}
BroadcastReceiver mBR = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int flag = intent.getIntExtra("Drop", 0);
switch (flag) {
case 0:
mText.setText("dropped!");
mImg.setImageResource(R.drawable.icon_argentina);
break;
}
}
};
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
button changes color even if it's already assigned
I have this problem: whenever I click on the div, I want to add background color. Forever. But background changes even if I click more (like a loop). How to set background color forever?
const blocks = document.querySelectorAll('.game div');
const liveNumber = document.querySelector('.lives-num');
let lives = 1;
function letTheGameBegin(e, r) {
const rand = Math.floor(Math.random() * 100);
if (rand < 40) {
e.target.style.backgroundColor = 'green';
} else if (rand < 60) {
e.target.style.backgroundColor = 'yellow';
lives++;
} else if (rand < 90) {
e.target.style.backgroundColor = 'red';
lives--;
} else {
e.target.style.backgroundColor = 'white';
}
liveNumber.innerHTML = lives;
if (lives === 0) {
//document.querySelector('.game-over').style.display = 'flex';
}
}
blocks.forEach(block => block.addEventListener('click', letTheGameBegin));
A:
I think you mean you only want to run the JS once per div.
Try this example and see if its what you need: jsfiddle
function letTheGameBegin(e, r) {
const rand = Math.floor(Math.random() * 100);
if(!e.target.style.backgroundColor){
if (rand < 40) {
e.target.style.backgroundColor = 'green';
} else if (rand < 60) {
e.target.style.backgroundColor = 'yellow';
lives++;
} else if (rand < 90) {
e.target.style.backgroundColor = 'red';
lives--;
} else {
e.target.style.backgroundColor = 'white';
}
liveNumber.innerHTML = lives;
if (lives === 0) {
//document.querySelector('.game-over').style.display = 'flex';
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Drop a column with a default constraint in SQL Server (IF EXISTS)
I am writing a sql script for dropping column and a default constraint. The following script works fine but i like to know if it is a right way of doing it.
Can i drop a default constraint with a column in one statement instead of using two separate ones?
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Employees_EmpID]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [DF_Employees_EmpID]
END
GO
BEGIN
ALTER TABLE [dbo].[Employees] DROP COLUMN [EmpID]
END
A:
In SQL Server 2005 upwards you can drop both the constraint and the column in one statement.
The syntax is
ALTER TABLE [ database_name . [ schema_name ] . | schema_name . ] table_name
DROP { [ CONSTRAINT ] constraint_name | COLUMN column } [ ,...n ]
The emphasis is on [ ,...n ], indicating multiple terms.
NB! Since the terms are processed sequentially, if the column being dropped is part of the constraint being dropped, then the constraint must be the first term, followed by the column term.
In your example:
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [DF_Employees_EmpID], COLUMN [EmpID]
So your code would be:
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Employees_EmpID]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [DF_Employees_EmpID], COLUMN [EmpID]
END
GO
In SQL Server 2016 they have introduced the IF EXISTS clause which removes the need to check for the existence of the constraint first e.g.
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT IF EXISTS [DF_Employees_EmpID], COLUMN IF EXISTS [EmpID]
A:
Here is another way to drop a column & default constraints with checking if they exist before dropping them:
-------------------------------------------------------------------------
-- Drop COLUMN
-- Name of Column: Column_EmployeeName
-- Name of Table: table_Emplyee
--------------------------------------------------------------------------
IF EXISTS (
SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'table_Emplyee'
AND COLUMN_NAME = 'Column_EmployeeName'
)
BEGIN
IF EXISTS ( SELECT 1
FROM sys.default_constraints
WHERE object_id = OBJECT_ID('[dbo].[DF_table_Emplyee_Column_EmployeeName]')
AND parent_object_id = OBJECT_ID('[dbo].[table_Emplyee]')
)
BEGIN
------ DROP Contraint
ALTER TABLE [dbo].[table_Emplyee] DROP CONSTRAINT [DF_table_Emplyee_Column_EmployeeName]
PRINT '[DF_table_Emplyee_Column_EmployeeName] was dropped'
END
-- ----- DROP Column -----------------------------------------------------------------
ALTER TABLE [dbo].table_Emplyee
DROP COLUMN Column_EmployeeName
PRINT 'Column Column_EmployeeName in images table was dropped'
END
--------------------------------------------------------------------------
-- ADD COLUMN Column_EmployeeName IN table_Emplyee table
--------------------------------------------------------------------------
IF NOT EXISTS (
SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'table_Emplyee'
AND COLUMN_NAME = 'Column_EmployeeName'
)
BEGIN
----- ADD Column & Contraint
ALTER TABLE dbo.table_Emplyee
ADD Column_EmployeeName BIT NOT NULL
CONSTRAINT [DF_table_Emplyee_Column_EmployeeName] DEFAULT (0)
PRINT 'Column [DF_table_Emplyee_Column_EmployeeName] in table_Emplyee table was Added'
PRINT 'Contraint [DF_table_Emplyee_Column_EmployeeName] was Added'
END
GO
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to change my project name Arabic name?
how to change my project name becouse I want it to Appare on mobile under the logo when its run the problem is I want to chane the name in to an Arabic name on android studio ?? it will not accapet
error massge invald pakage name :(
thank you
A:
You will need to create a folder in the res/ folder with values-ar/ folder and create a string.xml in the value-ar/ folder and have the arabic names in this strings.xml file
You can refer to http://developer.android.com/guide/topics/resources/providing-resources.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java: Component.printAll() problem
I'm trying to print a JFrame using the PrintUtilities Class:
package util;
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
public class PrintUtilities implements Printable {
private Component componentToBePrinted;
public static void printComponent(Component c) {
new PrintUtilities(c).print();
}
public PrintUtilities(Component componentToBePrinted) {
this.componentToBePrinted = componentToBePrinted;
}
public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
public int print(Graphics g, PageFormat pf, int page) throws
PrinterException {
if (page > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
/* Print the entire visible contents of a java.awt.Frame */
componentToBePrinted.printAll(g2d);
return PAGE_EXISTS;
}
public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}
public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}
}
Here is the source for the JFrame:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* NewJFrame.java
*
* Created on Jun 24, 2010, 12:24:17 PM
*/
package billing.print;
public class NewJFrame extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
new util.PrintUtilities(rootPane).print();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel2.setText("jLabel2");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("jLabel1");
jLabel3.setText("jLabel3");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(jLabel1)
.addGap(87, 87, 87)
.addComponent(jLabel3)
.addContainerGap(191, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(25, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(65, 65, 65)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
This is a screenshot of the JFrame :
http://img43.imageshack.us/img43/1980/48727815.jpg
And this is what the print (xps) came out to be:
http://img526.imageshack.us/img526/9954/47028546.jpg
What am i doing wrong here?
A:
I get exactly the same result when attempting to print to an .xps, but it does print correctly when I choose to save as to the Microsoft Office Document Image Writer (.tif) or directly to my printer.
Does your target have to be an .xps file or were you just using that for testing?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MEAN Stack File uploads
I've recently started programming with the MEAN Stack, and I'm currently implementing some sort of social network. Been using the MEAN.io framework to do so.
My main problem right now is getting the file upload to work, because what I want to do is receive the file from the form into the AngularJS Controller and pass it along with more info's to ExpressJS so I can finally send everything to MongoDB. (I'm building a register new user form).
I dont want to store the file itself on the database but I want to store a link to it.
I've searched dozens of pages on google with different search queries but I couldn't find anything that I could understand or worked. Been searching for hours to no result. That's why I've came here.
Can anyone help me with this?
Thanks :)
EDIT: Maybe a bit of the code would help understand.
The default MEAN.io Users Angular controller which I'm using as foundation has this:
$scope.register = function(){
$scope.usernameError = null;
$scope.registerError = null;
$http.post('/register', {
email: $scope.user.email,
password: $scope.user.password,
confirmPassword: $scope.user.confirmPassword,
username: $scope.user.username,
name: $scope.user.fullname
})//... has a bit more code but I cut it because the post is the main thing here.
};
What I want to do is:
Receive a file from a form, onto this controller and pass it along with email, password, name, etc, etc and be able to use the json on expressjs, which sits on the server side.
The '/register' is a nodejs route so a server controller which creates the user (with the user schema) and sends it to the MongoDB.
A:
I recently did something just like this. I used angular-file-upload. You'll also want node-multiparty for your endpoint to parse the form data. Then you could use s3 for uploading the file to s3.
Here's some of my [edited] code.
Angular Template
<button>
Upload <input type="file" ng-file-select="onFileSelect($files)">
</button>
Angular Controller
$scope.onFileSelect = function(image) {
$scope.uploadInProgress = true;
$scope.uploadProgress = 0;
if (angular.isArray(image)) {
image = image[0];
}
$scope.upload = $upload.upload({
url: '/api/v1/upload/image',
method: 'POST',
data: {
type: 'profile'
},
file: image
}).progress(function(event) {
$scope.uploadProgress = Math.floor(event.loaded / event.total);
$scope.$apply();
}).success(function(data, status, headers, config) {
AlertService.success('Photo uploaded!');
}).error(function(err) {
$scope.uploadInProgress = false;
AlertService.error('Error uploading file: ' + err.message || err);
});
};
Route
var uuid = require('uuid'); // https://github.com/defunctzombie/node-uuid
var multiparty = require('multiparty'); // https://github.com/andrewrk/node-multiparty
var s3 = require('s3'); // https://github.com/andrewrk/node-s3-client
var s3Client = s3.createClient({
key: '<your_key>',
secret: '<your_secret>',
bucket: '<your_bucket>'
});
module.exports = function(app) {
app.post('/api/v1/upload/image', function(req, res) {
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
var file = files.file[0];
var contentType = file.headers['content-type'];
var extension = file.path.substring(file.path.lastIndexOf('.'));
var destPath = '/' + user.id + '/profile' + '/' + uuid.v4() + extension;
var headers = {
'x-amz-acl': 'public-read',
'Content-Length': file.size,
'Content-Type': contentType
};
var uploader = s3Client.upload(file.path, destPath, headers);
uploader.on('error', function(err) {
//TODO handle this
});
uploader.on('end', function(url) {
//TODO do something with the url
console.log('file opened:', url);
});
});
});
}
I changed this from my code, so it may not work out of the box, but hopefully it's helpful!
A:
Recently a new package was added to the list of packages on mean.io. It's a beauty!
Simply run:
$ mean install mean-upload
This installs the package into the node folder but you have access to the directives in your packages.
http://mean.io/#!/packages/53ccd40e56eac633a3eee335
On your form view, add something like this:
<div class="form-group">
<label class="control-label">Images</label>
<mean-upload file-dest="'/packages/photos/'" upload-file-callback="uploadFileArticleCallback(file)"></mean-upload>
<br>
<ul class="list-group">
<li ng-repeat="image in article.images" class="list-group-item">
{{image.name}}
<span class="glyphicon glyphicon-remove-circle pull-right" ng-click="deletePhoto(image)"></span>
</li>
</ul>
</div>
And in your controller:
$scope.uploadFileArticleCallback = function(file) {
if (file.type.indexOf('image') !== -1){
$scope.article.images.push({
'size': file.size,
'type': file.type,
'name': file.name,
'src': file.src
});
}
else{
$scope.article.files.push({
'size': file.size,
'type': file.type,
'name': file.name,
'src': file.src
});
}
};
$scope.deletePhoto = function(photo) {
var index = $scope.article.images.indexOf(photo);
$scope.article.images.splice(index, 1);
}
Enjoy!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Alternatives for sigmoid curve starting from 0 with interpretable parameters
I am looking for alternative of sigmoid curves going through $(0,0)$, whose parameters can be sensed by eyeballing the function graph. As an example, consider this curve:
$$f(x) = {{a x ^ b} \over 1 + a x ^ b}$$
Where $ a, b $ are meaningless parameters without any straightforward interpretation. However, we can write the curve equation in such a way that both parameters will be meaningful. Imagine new parameters $c, d$ such that:
$$\begin{cases} f (c) = 0.1 \\ f (d) = 0.9 \end{cases}$$
Then expressing the curve with parameters a, b defined as follows, that is by parameters c, d, does the job.
$$\displaystyle{a}={9}\cdot{d}^{{-{b}}}$$
$$\displaystyle{b}=\frac{{-{4}\cdot \log{{\left({3}\right)}}}}{ \log{{\left(\frac{c}{{d}}\right)}}}$$
So looking at the example below, we can easily guess the values of parameters c, d. The function is in 10% and 90% value in approximately $x=1$ (parameter c) and $x=3$ (parameter d). Job done.
https://www.desmos.com/calculator/fmalvakguo
Why I ask for alternatives? The curve equation lacks "symmetry." I do not ask for exact symmetry but what I mean is that the function above $f(d)=0.9$ approaches asymptote of 1 very slowly. While below $f(c)=0.1$ the function gets to zero quite quickly.
A:
just putting this out there as a potential answer and hopefully encouraging others to do the same ... how about the Weibull "stretched exponential" function
$$f(x)=1-e^{-{\left(\frac{x}{a}\right)}^{b}}$$
where $b>2$
depending on the value of $b$ (pictured in graph are $b=3,4,5$), the symmetry can vary quite a bit, while $a$ sets the scale for $x$-axis
one can reexpress the $a$ and $b$ parameters as a function of $c$ and $d$ as provided in problem definition $$f(c)=0.1$$ and $$f(d)=0.9$$
and then, for instance, $$b=\frac{\ln \left(-\ln 0.1 \right) - \ln \left(-\ln 0.9 \right)}{\ln d - \ln c}$$ with $$a=c \left( -\ln 0.9 \right)^{-1/b}$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
$S(x)=\frac{x^4}{2\cdot 4}+\frac{x^6}{2\cdot 4\cdot 6}+\frac{x^8}{2\cdot4\cdot6\cdot8}+\cdots$
Find the sum of $$S(x)=\frac{x^4}{2\cdot 4}+\frac{x^6}{2\cdot 4\cdot 6}+\frac{x^8}{2\cdot4\cdot6\cdot8}+\cdots$$
What I did so far:
It's trivial that
$$S'(x)-xS(x)=\frac{x^3}{2}-\lim_{n\to\infty}\frac{x^{2n}}{n!2^{{n(n+1)}/2}}$$
and $$\lim_{n\to\infty}\frac{x^{2n}}{n!2^{{n(n+1)}/2}}=0$$
Solve this ODE I got
$$S(x)=\frac{x^4}{8}e^x+Ce^x$$
And $S(x)=0$ , So $C=0$.
Finally, I got $S(x)=\frac{x^4}{8}e^x$
The problem is when I expand the function I got into power series, it looks different from the original one. So I may make some mistakes but I can't tell. Please help.
A:
The $r+2(r\ge0)$th term $$T_{r+2}=\dfrac{x^{2r}}{2^r r!}=\dfrac{(x^2/2)^r}{r!}$$
As $e^y=\sum_{r=0}^\infty\dfrac{y^r}{r!},$
$$\sum_{r=2}^\infty\dfrac{x^{2r}}{2^r r!}=e^{x^2/2}-T_0-T_1=?$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Use Powershell to Find Stored Procedures in SSIS Packages
I'm attempting to using PowerShell to search all SSIS Packages within a directory, and return the following:
The path and name of the file
The line containing the stored procedure name, i.e. "exec mystoredproc"
The criteria I'd like to use to search is simply "exec", or "exec or execute" if possible, and I'd like the space at the end of the string following exec to be the delimiter as far as what is returned.
I've tried:
Get-ChildItem -recurse | Select-String -pattern "exec" | group path | select name
However this only returns the file name, not the additional text that is required.
If there is a better way to do this than PowerShell, I'm open to it, but based on what I've found so far this seemed to be the right path. Thank you in advance!
Edit:
Having continued to research, I've found that this command
Get-ChildItem -recurse | Select-String -pattern exec,execute | Select filename,linenumber
seems to give the correct file and line number for the commands I'm looking for. Is there some way to have the line that the linenumber references print instead of the number? I've looked at ForEach and Get-Content, but can't seem to get the syntax quite right.
A:
Here's a function that should prove useful for you:
function Get-StoredProcedure {
[CmdletBinding()]
[OutputType('System.Management.Automation.PSObject')]
param(
[Parameter(Position = 0, ValueFromPipeline)]
[System.IO.FileInfo[]] $Path = (Get-ChildItem -Recurse -File)
)
process {
foreach ($item in $Path) {
[pscustomobject]@{
'Path' = Split-Path -Parent -Path $item.FullName
'Name' = $item.Name
'Command' = ($item | Select-String -Pattern 'exec(ute)?\s[^\s]+').Matches.Value
}
}
}
}
This will go through whatever FileInfo objects you pass to it (do note to use -File with Get-ChildItem or filter out the PSIsContainer property). It returns an object with the path, filename, and command in a string in the form of exec(ute) <contiguous non-spaces>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails 3, Active Record query returns ActiveRecord::Relation object, instead of objects
I feel like this is a simple problem I'm having due to my misunderstanding of the new ActiveRecord query interface, but take this example:
>> Category.first.recipes
=> [ ... ] # array of recipes
However:
>> Category.where(:id => 1).recipes
=> NoMethodError: undefined method `recipes' for #<ActiveRecord::Relation:0x000001033dc9e0>
What's going on here? why does my where method return an ActiveRecord::Relation object? how can I retrieve the objects from the query here?
A:
This is actually intentional.
Category.where(:id => 1)
# Is Equivalent to Category.all(:conditions => {:id => 1}})
Category.where(:id => 1).first
# Is equivalent of Category.first(:conditions => {:id => 1}})
The objects are only retrieved when special methods like first, each etc are called. This is called lazy loading which is a great when you want to cache your views. Read more about why here.
A:
Category.where(:id => 1).recipes
Returns an array. If you simply do Category.where(:id => 1).first.recipes it should work.
A:
But if you are just doing a where against the id, use the find method
Category.find(1) will return a Category object.
So:
Category.find(1).recipes
|
{
"pile_set_name": "StackExchange"
}
|
Q:
fade in and move down
I have an animation set on my homepage headline using CSS to make it fade in when the page loads.
I have seen on other sites a really impressive animation that will fade in the title and move it down slightly.
How would I have to alter my code to be able to achieve this?
<div class="homepage">
<div class="headline">
<h1><span>WELCOME</span></h1>
</div>
<div class="subheadline">
<h1>
<span>To the home of</span>
</h1>
</div>
<div class="subheadline">
<h1>
<span>Multimedia Journalist</span>
</h1>
</div>
<div class="subheadline">
<h1>
<span>Dan Morris</span>
</h1>
</div>
<a href="#contact" class="smoothScroll" id="contactlink">Let's talk</a>
<div class="down-link">
<a class="w-downlink" href="#about">
<i class="fa fa-chevron-down"></i>
</a>
</div>
</div>
.headline {
height: auto;
width: 75%;
margin-left: 78px;
margin-top: 120px;
margin-right: auto;
font: 200 18px/1.3 'Roboto', 'Helvetica Neue', 'Segoe UI Light', sans-serif;
font-size: 12px;
font-weight: 200;
color: #676767;
text-align: left;
opacity: 0;
}
@-webkit-keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.fadeIn {
-webkit-animation: fadeIn 1s ease-in .5s both;
animation: fadeIn .1s ease-in .5s both;
}
A:
Simply use the top property along with position: relative;:
https://jsfiddle.net/svArtist/sc7dduue/
.headline {
height: auto;
width: 75%;
margin-left: 78px;
margin-top: 120px;
margin-right: auto;
font: 200 18px/1.3 'Roboto', 'Helvetica Neue', 'Segoe UI Light', sans-serif;
font-size: 12px;
font-weight: 200;
color: #676767;
text-align: left;
opacity: 0;
}
@-webkit-keyframes fadeIn {
0% {
opacity: 0;
top: -40px;
}
100% {
opacity: 1;
top: 0px;
}
}
@keyframes fadeIn {
0% {
opacity: 0;
top: -40px;
}
100% {
opacity: 1;
top: 0px;
}
}
.fadeIn {
position:relative;
-webkit-animation: fadeIn 1s ease-in .5s both;
animation: fadeIn 1s ease-in .5s both;
}
<div class="homepage">
<div class="headline fadeIn">
<h1><span>WELCOME</span></h1>
</div>
<div class="subheadline">
<h1><span>To the home of</span></h1></div><div class="subheadline"><h1><span>Multimedia Journalist</span></h1></div>
<div class="subheadline"><h1><span>Dan Morris</span></h1></div>
<a href="#contact" class="smoothScroll" id="contactlink">Let's talk</a>
<div class="down-link"><a class="w-downlink" href="#about"><i class="fa fa-chevron-down"></i></a></div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CSS how to break flow in just one direction
Motivation
CSS does not allow styling the options of an html select component, so I'm building a custom "component" to do so.
The challenge is this
Along the x-direction it needs to keep the inline flow.
Along the y-direction, it needs to be able to overlap content below it.
Here's an example (does not break flow)
http://jsfiddle.net/4tyvLmqn/1
html
<div class="dropdown">
<div class="item selected">asdflkhj asdf adf</div>
<div class="item">b</div>
<div class="item">c</div>
<div class="item">ad fds adfs dfsa fsd fasd</div>
<div class="item">e</div>
</div>
<hr />
This should not move down
<hr />
JS (click handler - there may be a pure CSS way to do this)
document.querySelector('.dropdown .selected').addEventListener('click', e => {
e.target.parentElement.classList.toggle('isOpen')
})
SCSS
.dropdown {
display: inline-flex;
flex-direction: column;
justify-content: center;
align-items: stretch;
user-select: none;
border: 1px solid gray;
}
.item {
visibility: hidden;
height: 0;
&.selected {
visibility: visible;
cursor: pointer;
height: auto;
}
.isOpen & {
visibility: visible;
height: auto;
}
}
A:
Simply keep a fixed height then adjust overflow (visible/hidden). You can also consider a max-height in case you will have a lot of elements.
const dropdown = document.querySelector('.dropdown');
dropdown.addEventListener('click', e => {
dropdown.classList.toggle('isOpen')
});
.dropdown {
display: inline-flex;
flex-direction: column;
justify-content: flex-start;
align-items: stretch;
user-select: none;
border: 1px solid gray;
height: calc(1em + 2 * 0.5em);
overflow: hidden;
}
.isOpen {
overflow: visible;
}
.background {
background-color: #fff;
z-index: 1;
border: inherit;
margin: -1px;
max-height: calc(5*(1em + 2 * 0.5em));
}
.isOpen .background {
overflow:auto;
flex-shrink:0;
}
.item {
padding: 0.5em;
cursor: pointer;
}
<div class="dropdown">
<div class="background">
<div class="item">Select an Item</div>
<div class="item">b</div>
<div class="item">c</div>
<div class="item">ad fds adfs dfsa fsd fasd</div>
<div class="item">e</div>
<div class="item">ad fds adfs dfsa fsd fasd</div>
<div class="item">e</div>
<div class="item">ad fds adfs dfsa fsd fasd</div>
<div class="item">e</div>
</div>
</div>
<hr /> This should not move down
<hr />
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Decrypt SSL traffic with the openssl command line tool - continued part 3
From my previous questions/thread starting part 1 and follow up part 2 following my guided explanation since my files/data I am capturing is binary in nature I used the following openssl commands where I began with my premaster secret derived from:
openssl rsautl -in cpre.key -inkey key.pem -decrypt -out spre.key
This created my 48 byte server pre master secret file spre.key (I think is correct) and in decimal for (viewing using bed) as:
003 003 203 048 063 215 047 196 221 221 221 014 019 072 011 100 217 080 111 073 217 026 234 082 022 217 232 025 096 063 115 080 016 094 015 170 148 126 092 118 109 228 246 149 208 195 044 220Hex: 0303CB303FD72FC4DDDDDD0E13480B64D9506F49D91AEA5216D9E819603F7350105E0FAA947E5C766DE4F695D0C32CDC
And concatenating the literal "master secret" + client.random + server.random I created mseed.key and again viewing with bed the same way as decimal I created:
109 097 115 116 101 114 032 115 101 099 114 101 116 173 212 147 215 014 129 225 102 157 027 001 125 167 097 014 085 064 025 114 025 024 248 096 254 044 235 151 130 033 151 015 133 251 114 232 095 213 076 194 057 175 106 225 088 206 069 187 050 168 031 217 080 198 061 180 043Hex: 6D617374657220736563726574ADD493D70E81E1669D1B017DA7610E554019721918F860FE2CEB978221970F85FB72E85FD54CC239AF6AE158CE45BB32A81FD950C63DB42Bfor a total of 69 bytes
Next I put that together and since I was advised that the data being in binary files I used the following to generate the master secret and keys.
openssl dgst -sha256 -hmac spre.key <mseed.key -binary >a1
openssl dgst -sha256 -hmac spre.key <a1 -binary >a2
openssl dgst -sha256 -hmac spre.key <a2 -binary >a3
openssl dgst -sha256 -hmac spre.key <a3 -binary >a4
This created 4 32 byte files.
followed up by creating the keys with:
cat a1 mseed.key | openssl dgst -sha256 -hmac spre.key -binary >k1
cat a2 mseed.key | openssl dgst -sha256 -hmac spre.key -binary >k2
cat a3 mseed.key | openssl dgst -sha256 -hmac spre.key -binary >k3
cat 42 mseed.key | openssl dgst -sha256 -hmac spre.key -binary >k4
This created 4 32 byte files.
Following along with the examples I was given and reading the RFC as I understand it the master key at this point would be the first 48 bytes of a1+a2 is that correct or did I miss something? Since I'm not actually able to see what the master_secret PRF returns or is doing I think from running the command line as above that is how I would get the master secret.
Thanks
David
A:
First, your mseed file (the label+seed value in the PRF) should be 77 bytes, not 69. You must have messed up the client and/or server nonces somehow.
Second, -hmac spre.key is badly wrong. It uses the actual characters s p r e . k e y i.e. the octets 73 70 72 65 2e 6b 65 79 as the HMAC key. You need to use the value of the decrypted premaster secret, which is the contents of your spre.key file. And because that is binary data that can include bytes which are special character codes like null, tab, dollarsign, quote, backslash, delete, etc. you can't safely pass it directly, as -hmac {key} or even -hmac '{key}'; instead you need to use -mac hmac -macopt hexkey:{hex key value} as I showed in the previous answer, except using the actual hex key value you showed in this Q namely 0303CB30...2CDC.
Third, as I showed in the previous answer, you concatenate the results of the second layer of HMACs i.e. in my notation k1,k2,... to form the output (which in that example was 100 octets):
$ cat k1 k2 k3 k4 | head -c100 | xxd
but as I went on to say:
... for the actual TLS1.2 handshake also, adjusted for the correct lengths: 48 for the master secret, and depending on the ciphersuite for the working keys.
For the first (premaster-to-master) derivation you need 48 octets, so you only need the first two chunks of 32 (a0->a1->a2 a1+a0->k1 a2+a0->k2) then concatenate k1+k2 and take the first 48 octets.
For the second (master-to-working) derivation the length you need depends on the ciphersuite that was negotiated. You said you are using RSA-with-AES256CBC-SHA which (in TLS1.2, or 1.1 but not 1.0) needs 40 octets of HMAC keys and 64 octets of encryption keys totalling 104 octets. For 104 ocets you need to compute 4 chunks of 32, concatenate k1+k2+k3+k4, and parcel it out to client-MAC, server-MAC, client-encryption, server-encryption in that order. See 6.3 of the RFC. Also note that the label is different, and for this derivation the seed is (label+)server_random+client_random, not (label+)client_random+server_random as in the first one.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Multiple Model Classes for same firebase element
I'm working with a application that used Firebase as data repository. I'm just refactor whole my app to implement Clean Architecture and RxJava. Doing everything in this way I found a problem managing my model objects.
Here is my problem: I have a Post.class with the same fields and values that I can retrieve from Firebase database reference:
public Post(Author author, String full_url, String full_storage_uri, String thumb_url, String thumb_storage_uri, String text, Object timestamp) {
this.author = author;
this.full_url = full_url;
this.text = text;
this.timestamp = timestamp;
this.thumb_storage_uri = thumb_storage_uri;
this.thumb_url = thumb_url;
this.full_storage_uri = full_storage_uri;
}
Everything fine for now. My problem appear when I retrieve the data from my Observer in my repository class:
@Override
public Observable<List<Post>> getPosts(final String groupId){
return Observable.fromAsync(new Action1<AsyncEmitter<List<Post>>>() {
@Override
public void call(final AsyncEmitter<List<Post>> listAsyncEmitter) {
final ValueEventListener PostListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
final List<Post> postList = new ArrayList<>();
Log.e("Count ", "" + snapshot.getChildrenCount());
//For every child, create a Post object
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Post post = postSnapshot.getValue(Post.class);
Log.e("new post added ", postSnapshot.getKey());
//Set the databaseReference to the object, which is needed later
post.setRef(postSnapshot.getKey());
postList.add(post);
}
listAsyncEmitter.onNext(postList);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e("The read failed: ", databaseError.getMessage());
}
};
//Remove listener when unsuscribe
listAsyncEmitter.setCancellation(new AsyncEmitter.Cancellable() {
@Override
public void cancel() throws Exception {
getPostsRef().child(groupId).removeEventListener(PostListener);
}
});
//Set the listener
getPostsRef().child(groupId).addValueEventListener(PostListener);
}
}, AsyncEmitter.BackpressureMode.BUFFER);
}
With this observer I already manage all the listeners and data calls, my only problem is these lines:
//Set the databaseReference to the object, which is needed later
post.setRef(postSnapshot.getKey());
I think that is not a good practice to set the reference as a new field in the Post Model which should equal to my firebase Json Tree. So my question is: Is a good practice to create 2 different models? One like "dbPost" and "PostEntity". One with the firebase values and the other one with a builder from a dbPost and the new fields that I want to save(dbReference and maybe valueListener)?
A:
Finally what I did was create two different model class. One of them to retrieve and insert my database params from Firebase and another one used by my app to manage the data with the extra values that it need thought the application:
App model:
public class Post implements Parcelable{
private Author author;
private String full_url;
private String thumb_storage_uri;
private String thumb_url;
private String text;
private Object timestamp;
private String full_storage_uri;
private String ref;
private Achivement post_achivement;
private long post_puntuation;
public Post() {
// empty default constructor, necessary for Firebase to be able to deserialize blog posts
}
[......]
Firebase Model:
public class NetworkPost {
private Author author;
private String full_url;
private String thumb_storage_uri;
private String thumb_url;
private String text;
private Object timestamp;
private String full_storage_uri;
private Achivement post_achivement;
private long post_puntuation;
public NetworkPost() {
// empty default constructor, necessary for Firebase to be able to deserialize blog posts
}
[...]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VSCode multiple/many tasks with keybinds
I would like to add more then 2 keybinds to more then 2 tasks. Like about 5-10.
Right now I have this:
// Place your key bindings in this file to overwrite the defaults
[
{ "key": "ctrl+alt+s", "command": "workbench.action.tasks.test" },
{ "key": "ctrl+alt+d", "command": "workbench.action.tasks.build" }
]
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "npm",
"isShellCommand": true,
"showOutput": "always",
"suppressTaskName": true,
"tasks": [
{
"taskName": "npm start",
"isTestCommand": true,
"args": ["start"]
},
{
"taskName": "npm dist",
"isBuildCommand": true,
"args": ["run", "dist"]
}
]
}
How can you add more?
A:
With the updated version of vscode 1.10 you can now bind keys to any task. Here is the release doc describing this.
As per the example in the link you can do:
{
"key": "ctrl+h",
"command": "workbench.action.tasks.runTask",
"args": "tsc"
}
which binds ctrl+h to the task named tsc
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to not exit on failed download?
How do I download a file with WWW::Mechanize without exiting on failed downloads?
#!/usr/bin/perl
use strict;
use WWW::Mechanize;
my $mech = WWW::Mechanize->new();
$mech->get("http://google.com/test", ':content_file' => "tmp");
print "done";
A:
You can use autocheck => 0 in the constructor :
#!/usr/bin/perl
use strict;
use WWW::Mechanize;
my $mech = WWW::Mechanize->new(
# perldoc WWW::Mechanize | less +/autocheck
autocheck => 0
);
$mech->get("http://google.com/test", ':content_file' => "tmp");
# Now, need to check errors manually :
# test on the HTTP return code see :
# http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
my $retcode = $mech->status();
if ($retcode >= 400) {
warn("error getting url, HTTP code: [$retcode]\n");
}
print "done\n";
A:
use Try::Tiny
#!/usr/bin/perl
use strict;
use WWW::Mechanize;
use Try::Tiny;
my $mech = WWW::Mechanize->new();
try {
$mech->get("http://google.com/test", ':content_file' => "tmp");
}
catch {
print "failed: $_";
}; # <-- do not forget the semicolon
print "done";
Leave out the catch block if you just want to silence errors.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Strdup each line into the array?
I have to allocate an array of 1000 pointers to character strings, read in each character string from stdin and strdup each line into the array. I did the following:
char *array[1000];
int index = 0;
for (int i = 0; i < 1000; i++) {
scanf("%s", &array[i]);
strdup(array[i]);
}
I'm not sure if this is the correct way of going about it??
EDIT:
So, I need to plug the newline at the end of each line with a null character and I need to do it using the strlen function. I have the following:
// Plug the newline where the end of
// a line is equal to '0/'
index = strlen(array) - 1; // line 30
if (array[index] = '\n') { // line 31
array[index] = '\0';
}
But Im getting the following error:
linesort.c: In function ‘main’:
linesort.c:30: warning: passing argument 1 of ‘strlen’ from incompatible pointer type
/usr/include/string.h:399: note: expected ‘const char *’ but argument is of type ‘char **’
linesort.c:31: warning: assignment makes pointer from integer without a cast
linesort.c:31: warning: suggest parentheses around assignment used as truth value
Please advise!
A:
You need an intermediate array. You can't just store into uninitialized memory here scanf("%s", &array[i]);
char *array[1000];
char buf[50] ;
char buf2[50] ;
for (int i = 0; i < 1000; i++) {
scanf("%49s", buf);
snprintf( buf2 , sizeof( buf ) , "%s\n" , buf ) ;
array[i] = strdup( buf2 );
}
return 0 ;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Export without links
When exporting, links are converted to the relevant format. Is it possible to tell org to simply ignore links and only export their text? (that is, completely ignoring the link, not including it as plain text)
My case is for exporting to Markdown, but I believe a solution should apply to all export back-ends.
A:
If there were a general org export option to do so I would expect to see it documented here: http://orgmode.org/manual/Export-settings.html#Export-settings. Looking directly at the source I don't see an option in the markdown export engine to do so either. Some options:
Quick-and-Dirty Solution™
If you are looking for the Quick-and-Dirty Solution™. You can redefine the org-md-link function. The function can be trivially simple:
(defun my-org-md-link (link contents info) contents)
If that breaks something else in your output (unlikely) you can at the very least directly revise the output formatting lines like
(format "[%s](%s)" contents path)
with
(format "%s" contents path)
If you want to preserve the original behavior of the export engine in some circumstances you can register a derived export engine:
(org-export-define-derived-backend 'my-md 'md
:menu-entry
'(?M "Export to Markdown without links" (lambda (a s v b) (org-md-export-to-markdown a s v)))
:translate-alist '((link . my-org-md-link)))
Add a filter which removes the links generated by ox-md (both better and worse)
The org export engine does have a mechanism that allows you a degree of flexibility to control the output of an export. See Filter Markup and Advanced Configuration.
(defun custom-md-link-filter (link backend info)
"Rewrite markdown links in export to preserve link text only."
(if (eq backend 'md)
(replace-regexp-in-string "\\[\\([^]]*\\)\\]([^)]*)" "\\1" link)
link)
(add-to-list 'org-export-filter-link-functions
'custom-md-link-filter)
I agree with you; a potential general org export option would be useful and would appropriately belong in the core export engine, so the translator of the selected export engine wouldn't even get called. Kudos to you if you submit a feature request (I would +1 that). If you do submit one-- post a link here for others to track it
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is a simple process for designing an OOP system before coding it?
Whenever I was required to build a project, I always managed to build it, not beforehand devising a plan or design, but after first writing a class that was needed, fleshing out the entire project, building from the bottom-up. Now I know this is not the proper way to create software, but it is not easy for me to wrap my head around what is called Objected Oriented Analysis and Design. I can more easily understand top-down procedural design, for it consists in merely breaking down tasks into sub-tasks, things which have their counterpart in code, functions. But Object Oriented Analysis and Design I cannot easily understand, for I do not understand how one can know what classes they will need and how they will interact, unless they know how they will code them.
For once we introduce the concept of classes and objects into the design process, we can no longer design top-down, because we are no longer breaking down our problems into those things which can be implemented as procedures. Instead, according to what I have read on the subject, we must determine what classes are needed, and create various artifacts in Unified Modelling Language, which we can then use when we implement the software. But this kind of design process I do not understand. For how does one know which classes they will need, and how they will interact, unless they have already conceived of the whole system?
This then is my problem. I do not understand how to design an Object-Oriented System, although I do understand the concepts of Object Oriented Programming, and can use those concepts in any Object Oriented Programming language that I know. Therefore I need someone to explain to me what simple process I can use to design Objected Oriented Systems in a way that makes sense to me.
A:
Top down waterfall style OOAD does not ensure that the code you write is object oriented at all. I have seen mountains of strictly OOAD produced code that proves it. If OO is confusing you, don't look here for help. You wont find it. OO does NOT require you to design top down.
If diving into a class is how you like to code, so be it. Let me tell you a hint. Procrastinate.
It's amazing how easy it is to design classes by writing code that uses them even when they don't exist yet. Forget procedure. Forget structure. Just get yourself a nice consistent level of abstraction going and stick with it. Don't give into temptation and mix extra details into it. Anything that takes you out of the current abstraction can go be done in some method that might be on some other object that somehow knows whatever it needs to know. Don't build anything you can just ask to be handed to you.
Learn to write like that and you'll find you're doing OO without even trying very hard. This forces you to look at your objects from the point of view of how they are used (their interface) and which objects know about which other objects. Guess what a UML diagrams main two points are?
If you can get into that mode of thinking then what's left is architecture. We're all still figuring that out. From MVC to clean architecture to domain driven design. Study them and play. Use what works. If you find something 100% reliable come back and let me know. Been doing this for decades and I'm still looking.
A:
You claim to be able to use object-oriented techniques in your code, so by that you do know how to design an object-oriented system already, I believe your problem is more of a matter of when, not whether or not you can. You seem comfortable with object-oriented design in a short-term iterative way, instead of a long-term planning way.
When first developing a project it can be very difficult to plan and design, that's when agile development is favoured over waterfall development, as the grand scope of a waterfall plan will often not capture all of the complexities of a software project.
You assert that developing on-the-fly without an "initial plan" is:
"... not the proper way to create software ..."
If your problem is that your initial plan is not detailed enough, take a little more time to explain your first thoughts. What is the first part of the program you plan to write? What is it going to need? Perhaps don't even think of what objects to start with, instead think of what features and plan from there.
If your problem is that you are not confident in your documenting / design / UML skills, practice by documenting an existing project.
Personally I would recommend to not worry about your designs being perfectly object-oriented, most systems are not 100% object-oriented. The goal is to create a better understanding and visualisation of the system, not perfect abstraction. Object-orientation is not the silver bullet, it's just another tool on the belt.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Nested tables with filter in angular 2
I need to nest 2 tables, the second one with a filter over the first. I've create a pipe but its not working because of this error (Looks like the pipe is not found):
Error
This is the code of the page:
HTML
<table class="panelTable">
<tr *ngFor="let type of arrTypes">
<td>
<div class="title-1">{{'ASSESSMENTTYPE.' + type.Type | translate}}</div>
<table class="panelTaskTable">
<tr *ngFor="let t of arrTask | filterType: type.Type">
<td><h4>{{t.teacherName}}</h4></td>
<td>
<img src="./images/nochecked.png" *ngIf="t.Progress != 100" />
<img src="./images/checked.png" *ngIf="t.Progress == 100" />
</td>
</tr>
</table>
</td>
</tr>
TYPESCRIPT
import { Component, Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({ name: 'filterType' })
export class FilterType implements PipeTransform {
transform(items: Array<TaskDTO>, Type: string): Array<TaskDTO> {
if (!items)
return null;
else
return items.filter(item => item.Type === Type);
}
}
The expected result is something similar to this:
ExpectedResult
Any idea about how to solve this?
Thanks!
A:
You have to declare your custom pipe in app.module.ts.
...
import { FilterType } from './filterType';
@NgModule({
imports: [
BrowserModule,
...
],
declarations: [
AppComponent,
...
FilterType
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
I also recommend to rename your pipe to FilterTypePipe.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dynamic Casting in a Loop
It's difficult to explain what I'm trying to achieve here (so...sorry if I missed a glaringly obvious answer in my searching)...
I'm trying to dynamically instantiate an object based on a Class paired to a value in a HashMap. However, I've been having issues finding an approach that actually works. Currently, I'm doing something like this:
HashMap<String, Flag<?>> flags = new HashMap<String, Flag<?>>();
HashMap<String, Class> keys = new HashMap<String, Class>();
keys.put("test", BooleanFlag.class);
keys.put("thing", StringFlag.class);
keys.put("foo", DoubleFlag.class);
for (Map.Entry<String, Class> key : keys.entrySet()) {
try {
Class c = key.getValue();
Object obj = c.getConstructor(String.class, String.class).newInstance(key.getKey(), "test value that will be checked and coerced by one of the flag classes");
flags.put(key.getKey(), c.cast(obj));
} catch (Exception ex) {
//exception handling
}
}
In this current incarnation of the method, c.cast(obj) throws a compiler error about an Object being found where Flag is expected. Am I going about this horribly wrong/is this possible?
A:
May be the 'Factory pattern' is what you actually need?
public class Flag<T> {}
public interface FlagFactory<T> {
public Flag<T> newInstance();
}
public class BooleanFlagFactory implements FlagFactory<Boolean> {
public Flag<Boolean> newInstance() {
return new Flag<Boolean>();
}
}
public class StringFlagFactory<T> implements FlagFactory<String> {
public Flag<String> newInstance() {
return new Flag<String>();
}
}
HashMap<String, FlagFactory> factories = new HashMap<String, FlagFactory>();
public void test() {
factories.put("test", new BooleanFlagFactory());
factories.put("thing", new StringFlagFactory());
Flag flag = factories.get("test").newInstance();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
String to zip file
I use a webservice that returns a zip file, as a string, and not bytes as I expected. I tried to write it to the disk, but when I open it, it tells me that it is corrupt. What am I doing wrong?
string cCsv = oResponse.fileCSV;//this is the result from webservice
MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(cCsv));
using (FileStream file = new FileStream("test.zip", FileMode.Create, FileAccess.Write))
{
ms.WriteTo(file);
}
ms.Close();
A:
Ok, i solve the problem:
File.WriteAllBytes("testbase64.zip", Convert.FromBase64String(cCsv));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change connection string for each database in each server
Say i have 2 servers server 1 and server 2.
In each server there are x databases, each having a connection to a global database.
server1 has database1, datatabse2, database3.
server2 has database4, database5
We would have 2 files, one file containing the servers, and another containing the "databases"
then the loop would be:
Import-Module SqlServer
foreach ($server in $servers_file)
{
$Analysis_Server = New-Object Microsoft.AnalysisServices.Server
$Analysis_Server.connect("$server")
foreach ($database in $databases_file)
{
$database = $Analysis_Server.Databases.FindByName($database)
####### Setting connection property for $database #######
$database.DataSources[0].ConnectionString = "UserId=…;Password=…."
}
}
the problem here is this loop does not consider where a database belongs for the server.
for example, if i have the database file as:
database1
database2
database3
database4
database5
how can i make this loop know that it has to exit the inner loop when database1-3 has finished from server1, and now you have to move on to the outerloop to connect to server2 for databases4 and 5.
ConnectionInfo class: https://docs.microsoft.com/it-it/dotnet/api/microsoft.analysisservices.connectioninfo?view=sqlserver-2016
A:
Seeing your last comment on wanting to use a csv file to populate the Hashtable, you can do this:
Suppose your CSV looks like this
"Server","Database"
"server1","database1"
"server2","database4"
"server1","database2"
"server1","database3"
"server2","database5"
You can then read it in using Import-Csv and create a hash from it like this
$h = @{}
Import-Csv '<PATH_TO_THE_CSV_FILE>' | Group-Object Server | ForEach-Object {
$db = @()
foreach ($item in $_.Group) {
$db += $item.Database
}
$h += @{$($_.Name) = $db}
}
Depending on your version of PowerShell (I think you need at least 5.1 for this), you can simplify the previous by doing:
$h = @{}
Import-Csv 'D:\Code\PowerShell\StackOverflow\Databases.csv' | Group-Object Server | ForEach-Object {
$h += @{$($_.Name) = $_.Group.Database}
}
Next you can use the loop as described by thom schumacher:
foreach($server in $h.Keys){
$Analysis_Server = New-Object Microsoft.AnalysisServices.Server
$Analysis_Server.connect("$server")
foreach($db in $h[$server]) {
write-output "$server - has db $db"
$database = $Analysis_Server.Databases.FindByName($db)
####### Setting connection property for $database #######
$database.DataSources[0].ConnectionString = "UserId=…;Password=…."
}
}
Edit
From your comment I gather your csv file looks like this:
"Server","Database"
"server1", "database1, database2, database3"
"server2","database4, database5"
In that case, you can read it into a Hashtable like this:
$h = @{}
Import-Csv '<PATH_TO_THE_CSV_FILE>' | ForEach-Object {
$h += @{$($_.Server) = ($_.Database -split '\s*,\s*') }
}
If your CSV file does not have headers like above, user the -Header switch on the Import-Csv cmdlet to give the columns a name we can work with like this:
Import-Csv '<PATH_TO_THE_CSV_FILE>' -Header 'Server','Database'
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP and two-directional text searching
Given a text file with many strings.
If, for example, do a search for red apples, the following code:
$search = "red apples";
$contents = file_get_contents("file.txt");
$pattern = "/^.*$search*\$/m";
preg_match_all($pattern, $contents, $matches);
implode("\n", $matches[0]);
will return (along with other strings) the following one:
Plate with many red apples blah blah
I need to found the same string, but with searching for apples red. Are there any ways to do it?
Thanks.
A:
$search_inversed = implode(' ', array_reverse(explode(' ', $search)));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using VBA to insert/update image in PowerPoint?
I am making an interactive Powerpoint presentation that has previously read a text file from my local server (XAMPP) and displayed it. I'd like to now update it so that the user can hand-write their response, and it displays that on the slideshow. I have a jQuery plugin that lets someone use a stylus and it saves the 'drawing' as an image on the local server.
My question is, how can I insert the image into PowerPoint using a VBA Macro? Or since the image always will have the same file path, but will be replaced with a different image, can I somehow "Update" the image on the slide? Sorry if it's confusing.
This is the VBA I tried:
Sub insert()
Dim oPic As Shape
Set oPic = ActivePresentation.Slides(1).Shapes.AddPicture("http://localhost/image.png", False, True, 0, 0, -1, -1)
End Sub
I could also get the path of the image on the computer, not the server.
When I run the macro, I get a "file not found" error. Does anyone know what's wrong?
Thanks!
PS: If anyone's interested, the plugin is called Signature Pad.
A:
Looks like I can insert an image if it's in the exact same folder:
Sub insert()
Dim oPic As Shape
Set oPic = ActivePresentation.Slides(1).Shapes.AddPicture("image.png", False, True, 0, 0, -1, -1)
End Sub
This works, but if anyone knows how to go into another folder, please let me know. If I try folder/image.png or /folder/image.png as the file path, it doesn't work.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I get the value of 'PAGE_CACHE_SIZE' that is mentioned in 'man mount'?
How do I get the value of PAGE_CACHE_SIZE that is mentioned in man mount?
man mount:
Mount options for tmpfs
size=nbytes
Override default maximum size of the filesystem. The size is given in bytes, and rounded up to entire pages. The default
is half of the memory. The size
parameter also accepts a suffix % to limit this tmpfs instance to that percentage of your physical RAM: the default, when
neither size nor nr_blocks is specified, is size=50%.
nr_blocks=
The same as size, but in blocks of PAGE_CACHE_SIZE
A:
Page cache - is the place in RAM where files are stored before writing to disk or after reading from disk. It's reduces delays for I/O operations to/from SSD, HDD, CD ...
tmpfs is the filesystem that lives in RAM permanently so tmpfs lives in page cache.
So page cache lives in RAM and consists of pages.
Page - is the minimum chunk of memory which OS can handle and it size depend on hardware (MMU(memory management unit) in CPU). All operations with memory usually rounded to page size.
Get page size (one of the way):
$ getconf PAGESIZE
4096
PAGE_CACHE_SIZE in mount command means count of pages. It's easy to check:
# mkdir /mnt/trash
# mount -t tmpfs -o nr_blocks=1 tmpfs /mnt/trash/
$ mount | grep trash
tmpfs on /mnt/trash type tmpfs (rw,relatime,size=4k)
$ df -h|grep trash
tmpfs 4.0K 0 4.0K 0% /mnt/trash
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I filter on day & month from a date field?
Hello I'm still fairly new to drupal and views,
I'm trying to create a Birthday notifier which checks "today" in a view block.
Now users can turn in their birthdays on their profile using the date field which is set as: yyyy/mm/dd.
Now the simple thing was to create a filter on the date today, but because of the yyyy field it wil not show up on today's date.
What I'd like is to filter mm/dd on today. So for example if someone's birthdate is 1993/07/03, he'd be notified as today is this persons birthday.
Is there a way to do this or to create a work around for this?
A:
Maybe you could conjure up something with the Regular expression inside the Date Filter, but that is usually not a nice path.
I haven't tried it but maybe you can do it with Contextual Filters (Under Advanced settings in the third column in Views). There is a separate Contextual filter for month, and for day:
node.field_date (month) and node.field_date (day)
Configure them with Default values Current date.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Inserting image over 3mb via linq-to-sql
New day, new problem :-)
Code:
Client Side:
void abw_Closed(object sender, EventArgs e)
{
DbServiceClient sc = new DbServiceClient();
abw = (AddBlobWindow)sender;
fi = ((AddBlobWindow)sender).fi;
if ((bool)((AddBlobWindow)sender).DialogResult)
{
blob = new Blob();
binBlob = new Binary();
binaryBlob = new byte[fi.Length];
int n = fi.OpenRead().Read(binaryBlob,0,Convert.ToInt32(fi.Length));
binBlob.Bytes = binaryBlob;
blob.Content = binBlob;
blob.Signature = abw.tbSignature.Text;
blob.Size = (int)fi.Length;
sc.SaveBlobCompleted += new EventHandler<AsyncCompletedEventArgs>(sc_SaveBlobCompleted);
sc.SaveBlobAsync(blob);
}
}
Server side service code:
[OperationContract]
public void SaveBlob(Blob blob)
{
try
{
RichTekstModelDataContext dc = new RichTekstModelDataContext();
dc.Blobs.InsertOnSubmit(blob);
dc.SubmitChanges();
}
catch (Exception ex) { string s = ex.Message; }
}
The problem:
When I am trying to save blobs with Content field smaller than 3mb it works perfectly, but when blob exceedes 3 mb, I am getting "Not found" exception (---> error line) in Refernece.cs file
public void EndSaveBlob(System.IAsyncResult result) {
object[] _args = new object[0];
----> base.EndInvoke("SaveBlob", _args, result);
}
I have no idea how to fix it. I have set in web.config apropriate buffers sizes, but stil it doesn't work.
Thanks for help.
A:
OK. I have found a solution:
link to solution:
http://silverlight.net/forums/p/18162/61547.aspx
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Apache: allow local connections to bypass basic authentication
I'm using HTTPS+basic auth (AuthType Basic ... Require valid-user) to protect a resource, but I'd like to allow connections from localhost through, even if they aren't authenticated.
What's the simplest way of doing that?
A:
You can tell apache to allow connections from specific IP addresses, like this:
Allow from 192.168.0.1/24
Satisfy Any
If you add that to your authentication scheme it will allow any IP address in the 192.168.0.1 - 192.168.0.254 range to access your content.
A full example may look like this (I am using digest, just substitute with your basic code):
<Location />
Order deny,allow
Deny from all
AuthName "SomeSite"
AuthType Digest
AuthDigestProvider file
AuthDigestDomain http://somesite.com
AuthUserFile /etc/apache2/password.file
Require valid-user
Allow from 192.168.0.1/24
Satisfy Any
</Location>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error in creating a docker container from docker image
I am trying to use docker file for a flask app. I have this docker file(end of file):
CMD ["/usr/bin/python3 manage.py"]
it's been build successfully with the command sudo docker build -t server . then I run it with sudo docker run -dit -p 5000:5000 -t server:latest but I get :
6acfe48c74d96c12eeda2c2cc98e27d2e5478edaa44f2061336102f04cdf54c4
docker: Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"/usr/bin/python3 manage.py\": stat /usr/bin/python3 manage.py: no such file or directory": unknown.
Let me know if you need more information. ( I used which python3 and pasted the PATH and used ls and saw manage.py exists there)
A:
When you say:
CMD ["/usr/bin/python3 manage.py"]
You are directing the system to run exactly that file; but there is no file named python3 manage.py in the /usr/bin directory. If you have a separate command and arguments then they need to be two separate things in the CMD listing:
CMD ["/usr/bin/python3", "manage.py"]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
why '?' appears as output while Printing unicode characters in java
While printing certain unicode characters in java we get output as '?'. Why is it so and is there any way to print these characters?
This is my code
String symbol1="\u200d";
StringBuilder strg = new StringBuilder("unicodecharacter");
strg.insert(5,symbol1);
System.out.println("After insertion...");
System.out.println(strg.toString());
Output is
After insertion...
unico?decharacter
A:
Here's a great article, written by Joel Spolsky, on the topic. It won't directly help you solve your problem, but it will help you understand what's going on. It'll also show you how involved the situation really is.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Update any of a number of fields in an SQL statement
Is there any way to optionally update any of a number of fields in an SQL statement? I can only get so far as something like:
UPDATE Customer SET
ContactName = ? <=== what to do here if ? is null???
, CompanyName = ? <=== what to do here if ? is null???
, AddressId = ? <=== what to do here if ? is null???
, ...
WHERE CustomerId = ?
It must be a single statement due to a limitation of the wrapper layer and MySQL.
To clarify, I want to create one statement which will be run with one or more non-null values for the fields listed and will update only those fields where the value is not null, leaving the others alone.
This is for a RESTful update API where I don't want a separate statement for every possible combination of fields and I don't want to demand that the API caller supply every single field on the record, which would be unwieldy and would not be future-proof (adding a field breaks existing API calls). And because it's a REST API I am looking to map POST /customer/xxx?ContactName=...&CompanyName=... to update the record.
A:
Not entirely clear on your goal, but I think you're looking for the coalesce feature; it will return the first non-null value:
mysql> SELECT COALESCE(NULL,1); -> 1
mysql> SELECT COALESCE(NULL,NULL,NULL); -> NULL
So you can set a 'default' to use in case the value is null:
UPDATE Customer SET
ContactName = COALESCE(?, <Some default>)
...
If you don't want to change the field, just use the current value:
UPDATE Customer SET
ContactName = COALESCE(?, ContactName)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Perl regex missing trailing parentheses on some, but not all records?
my @info = `net view printserver2`;
foreach my $printer (@info)
{
$printer =~ /.+\s+Print\s+\((.+)\)/;
print "$1\n";
gives me:
16-83
16-84) HP DesignJet 755CM(C3198A
16-84b
16-85
16-SW
17-80
18-45) HP DesignJet 250C (D/A1
18-51) HP DesignJet 650C(C2859B
This is the original:
(16-83) HP Designjet 800 42 by HP
(16-84) HP DesignJet 755CM(C3198A)by HP
(16-84b) HP LaserJet 5100 Series PCL6
(16-85) HP Designjet T1100ps 44in HPGL2
(16-SW) HP LaserJet 4100 Series PCL6
(17-80) HP Color LaserJet 5500 PCL 6
(18-45) HP DesignJet 250C (D/A1) by HP
(18-51) HP DesignJet 650C(C2859B) by HP
What is wrong with my regular expression?
This is the result I want:
16-83
16-84
16-84b
16-85
16-SW
17-80
18-45
18-51
A:
Your regex is matching up to the last ")" on the line. You need to specify a non-greedy match:
$printer =~ /.+\s+Print\s+\((.+?)\)/;
The question mark after .+ means to stop at the first opportunity.
Or, even better, specify that no ")" can be matched:
$printer =~ /.+\s+Print\s+\(([^)]+)\)/;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is my jquery toggle class is not working on single click
I am using a jquery function for toggle effect for an icon so when I click on that icon the div will move to left and hide.. so only the icon will show on the page and when I click on that icon again the div will appear sliding from left I am able to achieve the function but the following function
$(document).ready(function() {
$(".demo-icon").click(function() {
if ($('.demo_changer').hasClass("active")) {
$(".demo_changer").animate({
"left": "-208px"
}, function() {
$('.demo_changer').toggleClass("active");
});
} else {
$('.demo_changer').animate({
"left": "0px"
}, function() {
$('.demo_changer').toggleClass("active");
});
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="demo_changer" style="padding-top:13px">
<div class="demo-icon customBgColor">
<i class="fa fa-bullhorn fa-spin fa-2x"></i>
</div>
<div class="form_holder">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="predefined_styles">
<div class="skin-theme-switcher">
<a href="campaign.html" target="_blank">
<h4>some text</h4>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
Thanks for any replies in advance.
A:
Just found out that you did not add the class active while pageload but yet displaying the div.
Change the below line
<div class="demo_changer" style="padding-top:13px">
as
<div class="demo_changer active" style="padding-top:13px">
While loading, your webpage shows the div but does not have the class active in the div tag
and while clicking for the first time, as per your script, it finds out that there is no active class in the tag and then adds the class active and your div is already visible... I hope you understood..
The issue may be that, the margin in <div class="row"> is overlapping the icon div, it might be a reason why clicking on that area does not trigger "click" event -- See image below
Try Adding css style as mentioned in image below -
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Configure FreeRTOS ISR stack size
Is there a separate stack for FreeRTOS ISR context ? Is it fixed or configurable ?
#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 256 )
#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 512 * 1024 ) )
From my understanding this Stack size is exclusively for general tasks and not for ISRs. Any insights would be helpful.
Adding more details : This is an exclusive FreeRTOS port and not available in the community. The architecture is arm926ej-s (This can support a full fledged linux kernel - MMU support, but there was a need for running RTOS on it).
A:
ISR Stack size are configured by startup code, in your port. There's two ISR: FIQ and IRQ, each has its own stack.
Here I have searched an ARM9 FreeRTOS Demo for its stacks configuration, follow the result:
FreeRTOS/Demo/ARM9_STR91X_IAR$ grep -sri "FIQ_STACK"
91x_init.s: SECTION FIQ_STACK:DATA:NOROOT(3)
91x_init.s: LDR SP, =SFE(FIQ_STACK)
STR91x_FLASH.icf:define block FIQ_STACK with alignment = 8, size = __ICFEDIT_size_fiqstack__ { };
STR91x_FLASH.icf: block CSTACK, block SVC_STACK, block IRQ_STACK, block FIQ_STACK,
91x_init_IAR.s:FIQ_Stack DEFINE USR_Stack-8 ; followed by FIQ stack
91x_init_IAR.s:ABT_Stack DEFINE FIQ_Stack-8 ; followed by ABT stack
91x_init_IAR.s: LDR SP, =FIQ_Stack
FreeRTOS/Demo/ARM9_STR91X_IAR$ grep -sri __ICFEDIT_size_fiqstack__
STR91x_FLASH.icf:define symbol __ICFEDIT_size_fiqstack__ = 0x10;
STR91x_FLASH.icf:define block FIQ_STACK with alignment = 8, size = __ICFEDIT_size_fiqstack__ { };
It means that stacks sizes are defined in STR91x_FLASH.icf file, or 91x_init_IAR.s, in the ARM9_STR91X_IAR Demo, accordingly with the compiler/startups you use to build.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What are all these unicorn processes? or are they threads?
I'm running an Ruby on Rails app using Unicorn. We configured our server to run three workers, but when I look at it with htop, I see what looks like the three workers and then, each of them have several sub-process, or are they threads? What's going on? What are they?
A:
Those processes are most probably threads. To figure out which are threads and which are child processes go to htop settings: F2 -> Display options and disable Hide userland threads or toggle Display threads in a different color.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Create redirect after registration Laravel
I want after successful registration I was redirected to successfull.blade.php , but for some reason it either gives a 404 error, that the page was not found, or that it always throws me to home ... I can’t handle it please help me.
After successful registration, I should be thrown to successfull.blade.php
Please help me.
RegistersUsers.php
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect()->to('/successfull');
}
RegisterController
protected function redirectPath()
{
if (Auth::user()->role_id==NULL) {
return '/successfull';
} else {
return '/successfull';
}
}
web.php
Auth::routes();
Route::get('/home', 'HomeController@getUser')->name('users');
Route::get('/successfull', 'Auth\RegisterController@redirectPath');
homecontroller
public function getUser(){
$user=auth()->user();
return view('home',[
'users' => $user,
]);
}
throws me to home because of homecontroller, but I want it to be only after login, and after registration I need to be redirected to another file
A:
Routes:
define a new function in HomeController named as success and call success.blade.php inside function.
Route::get('/successfull', 'HomeController@success');
RegisterController
if (Auth::user()->role_id != NULL) {
return redirect('/successfull');
}
RegistersUsers.php
after user account created successfully
redirect('/successfull')->withSuccess(' Account Created Successfully');
Hope it will help you :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jTextArea outprint text vertically
At the moment I am doing actions (clicking on menu items) and these actions are being stored in an arrayList. When I click a button this text is output in a long line (each item being printed one after another). I was wondering how I can change this so that when I click the button all of the test is printed vertically. Thank You!
Here is the code I am currently using!
jtaWoof.append(MyFrame.shape1.getArrayList()+"\n");
A:
Looks like you appending the contents of the ArrayList in one go. You should use a loop to iterate through the ArrayList and append each entry to jtaWoof:
ArrayList<String> list = MyFrame.shape1.getArrayList();
for(String s : list){
jtaWoof.append(s);
jtaWoof.append("\n");
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does $i ( LK-KL )$ represent a real quantity?
According to my textbook, it says that $i( LK-KL )$ represents a real quantity when $K$ and $L$ represent a real quantity. $K$ and $L$ are matrices. It says that this is because of basic rules. However, I was not able to recall my memories. Can anyone show the proof of this?
A:
The statement is that if $K$ and $L$ are Hermitian operators – which means
$$ K = K^\dagger, \quad L = L^\dagger$$
and it implies that the eigenvalues of $K,L$ are real and the eigenvectors with different eigenvalues are orthogonal to each other, then $i(KL-LK)$ (the same as yours) is also Hermitian. This is easily proved by computing the Hermitian conjugate of this $i(KL-LK)$ because the result is the same as this operator itself:
$$ [i(KL-LK)]^\dagger = i^\dagger (KL-LK)^\dagger = (-i) (L^\dagger K^\dagger - K^\dagger L^\dagger) = (-i)(LK-KL) = i(KL-LK).$$
I used $(AB)^\dagger = B^\dagger A^\dagger$ and $i^\dagger = i^* = -i$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Magento 2 : cannot save customer phone number
Using Magento 2.2, Backend, Customers. I cannot update or save suctomer telephone number, but after Save no message Error.
Customer -> All Customer -> Customers
NOTE: This is original code, not yet custom.
EDIT:
I see phone number in customer information edit form, But still not show in table.
Customer -> All Customer -> Customers
Customer Table -> Edit -> Address
A:
Customer phone number from the billing address. Once we add billding address for the customer then only the grid phone field can be validated.
Customer grid
Customer default billing address
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What everyday tasks can be adapted in a way that helps build muscles and technique for bouldering?
(This is related to "What hand and finger exercises help with climbing?" but asking for what can be done when not climbing/training.)
Like most climbers, I don't get to do as much as I'd like, and I rarely climb as well as I'd like, so I'm wondering if there are ways to squeeze training exercises in when I'm doing other things.
For example, if I'm carrying bags, I've started reducing the number of fingers I use, with a view to increasing the weight my fingers can support, and thus improve my ability when on small holds and pockets. (No idea how well that might work, but it demonstrates the type of things I mean).
Any types of improvement are welcome, though I am specifically looking at bouldering (free climbing), as opposed to roped/other climbing.
A:
Whilst walking about, clench your fist, then stretch your hand open again. repeat this 30 times (or whatever you want) and relax. Bit by bit, maybe one or two a day, increase the reps. Vary for speed and power.
You can do this whilst walking around.
A:
As I noted in my answer to that question, plasticene or stress balls work.
Also, you can use guitarist's finger exercisers
I do like your idea of using less fingers for carrying bags etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Delete Slow Query Log File
I was logging slow queries of my system. Now I have few queries to be optimized and reset the global slow_query_log variable to 0. Now I want to delete slow query log file mysqld-slow.log. can anyone tell me what is the standard way to do this ?
I am using Cent OS and do not want to delete or affect other log files (i.e. general log or binary log)
Thanks.
A:
As of 5.5.3, FLUSH LOGS will close and reopen the slowlog. (In old versions, FLUSH had no effect on the slowlog.)
So, on *nix OS, this should work without restarting the server:
rm (to delete) or mv the slowlog to another name. (Note: mysqld will continue to write to the file, even though you changed the name.)
FLUSH LOGS;. As of 5.5.3, you can limit the effect via FLUSH SLOW LOGS;
See http://bugs.mysql.com/bug.php?id=14104 and http://bugs.mysql.com/bug.php?id=60878
I would not turn off the slowlog -- next month someone will add a naughty query and you will want to know about it.
A:
or set
SET GLOBAL slow_query_log = 'OFF';
then clear the file and then
SET GLOBAL slow_query_log = 'ON';
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to customize foreign key column name using Entity Framework Code-first
I have the following model
public class Foo
{
public int Id { get; set; }
public IList<Bar> Bars { get; set; }
}
public class Bar
{
public int Id { get; set; }
}
When I generate the database schema from this using EF Code first it creates the following tables:
Foo
Id (PK, int, not null)
Bar
Id (PK, int, not null)
Foo_Id (FK, int null)
Is it possible to change the name of the Foo_Id foreign key using attributes?
EDIT: Here is the version that does what I need:
public class Foo
{
public int Id { get; set; }
[ForeignKey("AssignedToBarId")]
public IList<Bar> Bars { get; set; }
}
public class Bar
{
public int AssignedToBarId { get; set; }
public int Id { get; set; }
}
A:
I think it can be done like below:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity.Map(c => c.MapKey(u => u.Id, "AssignedToBarID"));
}
Or maybe:
[ForeignKey("AssignedToBarID")]
public IList<Bar> Bars { get; set; }
NOTE: I have not tested neither of them. These are just suggestions.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Uncaught ReferenceError: Popper is not defined - with Bootstrap 4 and Webpack 3.8.1
I am using the Visual Studio 2017 Angular template with .NET Core 2.0. The template has numerous older dependencies which I have updated, including to Angular 5.0.0. Running the vanilla template with Bootstrap 3.x.x works. However, using Bootstrap 4.0.0-beta.2 results in the following error:
Uncaught ReferenceError: Popper is not defined
I have followed the instructions here to the best of my ability:
http://getbootstrap.com/docs/4.0/getting-started/webpack/
I have looked at this issue:
Bootstrap 4: Uncaught ReferenceError: Popper is not defined
Per the solutions listed there, I have to to either register popper before bootstrap or to use the min version of boostrap since it comes with popper already. However, I am using webpack 2.5.1 (which I am just now learning) and I don't know how to implement either of those solutions in the webpack.config.js file which was provided as part of the template and includes the modification called out by the boostrap-webpack docs.
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
module.exports = (env) => {
// Configuration in common to both client-side and server-side bundles
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
context: __dirname,
resolve: { extensions: ['.js', '.ts'] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
{ test: /\.html$/, use: 'html-loader?minimize=false' },
{ test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot.browser.ts' },
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default'],
// In case you imported plugins individually, you must also require them here:
//Util: "exports-loader?Util!bootstrap/js/dist/util",
//Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown"
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
exclude: ['./**/*.server.ts']
})
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundleConfig = merge(sharedConfig, {
resolve: { mainFields: ['main'] },
entry: { 'main-server': './ClientApp/boot.server.ts' },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./ClientApp/dist/vendor-manifest.json'),
sourceType: 'commonjs2',
name: './vendor'
})
].concat(isDevBuild ? [] : [
// Plugins that apply in production builds only
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
exclude: ['./**/*.browser.ts']
})
]),
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
devtool: 'inline-source-map'
});
return [clientBundleConfig, serverBundleConfig];
};
Also, here is the main entry point file boot.browser.ts provided as part of the template:
import 'reflect-metadata';
import 'zone.js';
import 'bootstrap';
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module.browser';
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => {
// Before restarting the app, we create a new root element and dispose the old one
const oldRootElem = document.querySelector('app');
const newRootElem = document.createElement('app');
oldRootElem!.parentNode!.insertBefore(newRootElem, oldRootElem);
modulePromise.then(appModule => appModule.destroy());
});
} else {
enableProdMode();
}
// Note: @ng-tools/webpack looks for the following expression when performing production
// builds. Don't change how this line looks, otherwise you may break tree-shaking.
const modulePromise = platformBrowserDynamic().bootstrapModule(AppModule);
A:
I finally found out how to get past the error. I used the following lines in the main entry point boot.browser.ts file:
import * as $ from 'jquery';
//These two lines didn't remove the error
//import Popper from 'popper.js';
//import 'bootstrap';
//This one did remove the error. The bundle version of bootstrap includes popper in the correct order (according to the docs)
import 'bootstrap/dist/js/bootstrap.bundle.js';
Interestingly, the suggested code at the bootstrap github (https://github.com/twbs/bootstrap/issues/24648) was to use this line for the jquery import:
import $ from 'jquery'
instead of
import * as $ from 'jquery'
but the former caused this error:
Could not find a declaration file for module 'jquery'
However, I have no idea what the difference is between the two lines
|
{
"pile_set_name": "StackExchange"
}
|
Q:
javascript hide/show example - close divs
In this javascript hide/show example, how can I close all other divs when a div is selected?
<script TYPE="text/JavaScript">
function show_hide(id, show)
{
if (el = document.getElementById(id))
{
if (null==show) show = el.style.display=='none';
el.style.display = (show ? '' : 'none');
}
}
</script>
& don't tell me to use jQuery, becuase it won't run in some mobile environments that we use.
A:
I'd do it like this
var alldivs = document.getElementsByTagName("DIV");
for (var i=0;i<alldivs.length;i++){
var odiv = alldivs[i];
//we only need "other" divs, not the one we're working on
if ( (odiv.id) && (odiv.id!=id)) {
odiv.style.display="none";
}
}
(+ thanks for not asking for a jQuery solution:)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Forwarding domain path to other domains with a different port
I was wondering if forwarding like this was possible with any service like godaddy/dyndns/etc:
http://www.mydomain.com/path1 ---> http://mydomain.com:1234/
http://www.mydomain.com/path2 ---> http://domain2.com:5688/test1
http://www.mydomain.com/path3 ---> http://domain2.com:9873/test2
It would also be nice if the browser didn't show the ports, etc.
A:
What you would need is not a DNS-based solution, but a Reverse Proxying solution.
Most of the predominant web server technologies on the market offer this functionality to some extent, like:
Apache (with mod_proxy), IIS (with Application Request Routing) and nginx.
I don't have any experience with hosted reverse proxying, but I know that some hosting providers offer this capability.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I Set an Executable's Search Path?
I'm not using the default Visual Studio project path to build my program into, because I want to emulate a release, and write tools to search for resources. After tinkering with the settings, I've got VS to output to the right folder, and to copy the DLLs to a bin folder in the main folder. However, I can't get the .EXE it generates to find the DLLs, it will only find what's in it's directory, but I don't want to be messy like that. The debugger works fine, but it won't work standalone. How do I tell VS to tell the .EXE where to find it's DLLs? Do I have to edit the PATH? That seems messy, as I've never had good experiences with it. I've tried Project Settings -> VC++ Directories, but it still won't find it, as I'm assuming that that's for .LIB files.
Here is a diagram of my folder hierarchy.
-root
--bin
---[Required DLLs]
--data
---[Program Resources (images, sounds, configs, etc.)]
--Program.exe
Using Visual C++ 2010 Express Edition.
A:
How do I tell VS to tell the .EXE where to find it's DLLs?
Edit the Release Run Configuration and change the working directory where your dlls reside.
You will still have to run your exe through the ide for this to work.
Do I have to edit the PATH?
No
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Electrical engine calculations
The ElectricalEngine class responds to the horsepower message. Because efficiency is calculated in percent a programmer can mistakenly initialize it with an integer instead of a float.
class ElectricalEngine
attr_reader :volts, :current, :efficiency
def initialize(volts, current, efficiency)
@volts, @current, @efficiency = volts, current, efficiency
end
HP_IN_WATTS = 746
def horsepower
(volts * current * efficiency) / HP_IN_WATTS
end
end
puts ElectricalEngine.new(240, 90, .6).horsepower # correct
puts ElectricalEngine.new(240, 90, 60).horsepower # buggy
How would you handle this scenario?
Do nothing. It's the programmers responsibility to know the right datatype.
Rename efficiency to efficiency_as_float to make it clearer.
Rename efficiency to efficiency_as_percent and adjust horsepower's calculation.
Write a custom efficiency method to check the datatype and convert it accordingly.
Check efficiency type and raise an error if it's not a float.
Other
Solution four might look like this. Of course this conversion can happen in the initialize method too, but I think this is cleaner.
def horsepower
(volts * current * efficiency_as_float) / HP_IN_WATTS
end
def efficiency_as_float
if efficiency.is_a?(Integer) # what if 1 is passed in instead of 1.0?
efficiency / 100.to_f
else
efficiency
end
end
Solution 5 would look something like this:
def initialize(volts, current, efficiency)
raise "Efficiency must be a float" unless efficiency.is_a?(Float)
@volts, @current, @efficiency = volts, current, efficiency
end
Should ElectricalEngine own the responsibility of converting incorrect datatypes?
A:
my two cents : use duck-typing.
@efficiency = efficiency.to_f
... if it quacks like a float, then it is a float. This allows to leverage ruby's awesomeness with things like :
class EfficiencyProfile
def initialize(some_data, value)
@data = some_data
@efficiency_value = some_value
end
def to_f
@efficiency_value.to_f
end
end
e = EfficiencyProfile.new(some_big_chunk_of_data_about_engine_performance, 42)
ElectricalEngine.new(1,2,e) # would work without a complain
Dynamic typing sure is dangerous, but you have to embrace it if you want to benefit from it.
Checking the type explicitly is an half-arsed solution, because :
it is cumbersome, and you will never be as good at it than, say, a C compiler is
it will completely remove the sole benefit from dynamic typing : flexibility.
A:
I'd say pick #1: Do nothing (except, as m_x says, use to_f). But, if you really, really want to do something, pick #5: Raise an error. Specifically, I'd recommend raising a RangeError with a helpful message.
raise RangeError, "efficiency must be between 0 and 1" unless (0..1).cover?(efficiency.to_f)
As for this:
Because efficiency is calculated in percent a programmer can mistakenly initialize it with an integer instead of a float.
Yes, it can happen (I've made such mistakes myself), but using a 0..1 float is the more common approach (in my experience). It's usually only spreadsheets that deal with percentages as 0..100; in most programming (and math) contexts, "percent" means some 0..1 number. So calling it efficiency_as_percent could cause the opposite effect: People passing a 0..1 float where an int is required.
Either way, the efficiency isn't specifically percentage (although you might render it as such); it's just a ratio. A factor. Hence floats make more sense, as they allow you set a more precise value than 0..100.
Of course, you have to be a bit pragmatic about all this, so you don't end up implementing a strict type in a dynamically-typed language. For instance, you could also check volts and current - e.g. they probably shouldn't be negative. But then it quickly becomes a huge headache.
You might also ask, "well, what if I want to calculate the horsepower of an over-unity engine?". Well, you can't, if efficiency can't go above 1.0. But in a sense, it's just algebra. You've got a formula, and you can plug whatever you want into it. Whether it makes sense to plug certain values in doesn't change the math. From a practical standpoint, a 200% efficiency engine is of course impossible, but you can still do the math just fine. Heck, even a perfect, 100% efficiency engine is impossible. Sooo should you only allow 0...1 (half-open range)? If you don't allow 1.0 itself, then how close a value do you allow? 0.9? 0.99999?
Similarly, a zero-efficiency engine sounds like a mistake, so should you point that out too? And so on and so on...
Anyway, I'd be ok with checking efficiency, but I wouldn't bother with it myself. Leave it to the programmer to do things right or suffer the consequences. GIGO: Garbage In, Garbage Out.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CoreLocation not working in ios 8
I'm using Location service in my app.
But [CLLocationManager authorizationStatus] is kCLAuthorizationStatusNotDetermined both before [self.locationManager startUpdatingLocation];
code of project:
Implementation
#import <CoreLocation/CoreLocation.h>
@interface NewRunViewController () <CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
- (void)viewDidLoad
{
[super viewDidLoad];
[self startLocationUpdates];
}
- (void)startLocationUpdates
{
// Create the location manager if this object does not
// already have one.
if (self.locationManager == nil) {
self.locationManager = [[CLLocationManager alloc] init];
}
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = 10;
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
}
I also add NSLocationWhenInUseUsageDescription key into info.plist file.
And app also does not ask for user permission to use core location service.
Can anyone help me??
A:
Thank you guys for your answers. I found solution of problem. I checked the version of system like:
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
in startLocationUpdates method:
if(IS_OS_8_OR_LATER) {
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
}
}
Now it's working properly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Zookeeper vs In-memory-data-grid vs Redis
I've found different zookeeper definitions across multiple resources. Maybe some of them are taken out of context, but look at them pls:
A canonical example of Zookeeper usage is distributed-memory computation...
ZooKeeper is an open source Apache™ project that provides a centralized infrastructure and services that enable synchronization across a cluster.
Apache ZooKeeper is an open source file application program interface (API) that allows distributed processes in large systems to synchronize with each other so that all clients making requests receive consistent data.
I've worked with Redis and Hazelcast, that would be easier for me to understand Zookeeper by comparing it with them.
Could you please compare Zookeeper with in-memory-data-grids and Redis?
If distributed-memory computation, how does zookeeper differ from in-memory-data-grids?
If synchronization across cluster, than how does it differs from all other in-memory storages? The same in-memory-data-grids also provide cluster-wide locks. Redis also has some kind of transactions.
If it's only about in-memory consistent data, than there are other alternatives. Imdg allow you to achieve the same, don't they?
A:
https://zookeeper.apache.org/doc/current/zookeeperOver.html
By default, Zookeeper replicates all your data to every node and lets clients watch the data for changes. Changes are sent very quickly (within a bounded amount of time) to clients. You can also create "ephemeral nodes", which are deleted within a specified time if a client disconnects. ZooKeeper is highly optimized for reads, while writes are very slow (since they generally are sent to every client as soon as the write takes place). Finally, the maximum size of a "file" (znode) in Zookeeper is 1MB, but typically they'll be single strings.
Taken together, this means that zookeeper is not meant to store for much data, and definitely not a cache. Instead, it's for managing heartbeats/knowing what servers are online, storing/updating configuration, and possibly message passing (though if you have large #s of messages or high throughput demands, something like RabbitMQ will be much better for this task).
Basically, ZooKeeper (and Curator, which is built on it) helps in handling the mechanics of clustering -- heartbeats, distributing updates/configuration, distributed locks, etc.
It's not really comparable to Redis, but for the specific questions...
It doesn't support any computation and for most data sets, won't be able to store the data with any performance.
It's replicated to all nodes in the cluster (there's nothing like Redis clustering where the data can be distributed). All messages are processed atomically in full and are sequenced, so there's no real transactions. It can be USED to implement cluster-wide locks for your services (it's very good at that in fact), and tehre are a lot of locking primitives on the znodes themselves to control which nodes access them.
Sure, but ZooKeeper fills a niche. It's a tool for making a distributed applications play nice with multiple instances, not for storing/sharing large amounts of data. Compared to using an IMDG for this purpose, Zookeeper will be faster, manages heartbeats and synchronization in a predictable way (with a lot of APIs for making this part easy), and has a "push" paradigm instead of "pull" so nodes are notified very quickly of changes.
The quotation from the linked question...
A canonical example of Zookeeper usage is distributed-memory computation
... is, IMO, a bit misleading. You would use it to orchestrate the computation, not provide the data. For example, let's say you had to process rows 1-100 of a table. You might put 10 ZK nodes up, with names like "1-10", "11-20", "21-30", etc. Client applications would be notified of this change automatically by ZK, and the first one would grab "1-10" and set an ephemeral node clients/192.168.77.66/processing/rows_1_10
The next application would see this and go for the next group to process. The actual data to compute would be stored elsewhere (ie Redis, SQL database, etc). If the node failed partway through the computation, another node could see this (after 30-60 seconds) and pick up the job again.
I'd say the canonical example of ZooKeeper is leader election, though. Let's say you have 3 nodes -- one is master and the other 2 are slaves. If the master goes down, a slave node must become the new leader. This type of thing is perfect for ZK.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
D3.js Force Layout - showing only part of a graph
Good morning,
just starting with the awesome d3js library ...
I want to show only a portion of a graph with the force directed layout. The idea is to have one node declared as the "center" and show all nodes within a distance of two (for example) from this center node, the neighbors of the center node and the neighbors of the neighbors. If the user clicks on one of the displayed nodes it becomes the "new" center node and a different "subgraph" is displayed. I wonder if there is an example around implementing this kind of subgraph layout and if some kind of a "node-distance" algorithm is already implemented in d3js.
Thanks a lot
martin
UPDATE:
Just found the example Modifying a Force Layout which illuminates how to add and remove nodes and edges from a force directed layout.
A:
I just uploaded a "proof of concept level" of an interactive force directed subgraph.
http://justdharma.com/d3/sub-graph/
In this example I use backbonejs under the hood. Being the first time I implement something with backbonejs, I for sure use it in a very crude manner. While this example might illuminate one way how an interactive sub-graph can be achieved it is for sure not a template how to do it - as said just a proof of concept hack ...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Valid way of evaluating limits?
Calculate the following limits $$\lim_{x \to 0} \frac{e^{\sin x} - \sin^2x -1}{x},\,\,\,\,\,\,\,\, \lim_{x\to0} \frac{\sin x \cos x - x}{x^2 e^x}.$$
I've evaluated these using the asymptotic equivalences $$\sin x \sim_0 x, \, \,\,\,\cos x \sim_0 1$$ as follows:
$$\frac{e^{\sin x} - \sin^2x -1}{x} \sim_0 \frac{e^x - x^2 -1}{x} = \frac{e^x -1}{x} - x \to 1$$
and
$$\frac{\sin x \cos x - x}{x^2 e^x} \sim_0 \frac{x-x}{x^2 e^x} = 0.$$
Are my calculations correct?
A:
I wouldn't say asymptotic in this case. I would call it approximation (up to certain error). For example
$$\sin x = x +O(x^3),...$$
Your explanations are not correct (although incidently the results are correct). To see why it is wrong, try to the argument in the second case for $x^{2014}e^x$ instead of $x^2e^x$ in the denominator.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find on which $z=x+iy\in\mathbb{C}$ the function $f(z)=(\overline{z}+1)^3 - 3\overline{z}$ is differentiable
I'm solving past exam questions in preparation for an Applied Mathematics course. I came to the following exercise, which poses some difficulty. If it's any indication of difficulty, the exercise is only Part 3-Β of the sheet, graded for 10%
Find on which $z=x+iy\in\mathbb{C}$ the function $f(z)=(\overline{z}+1)^3 - 3\overline{z}$ is differentiable
My first thought is that I have to prove $f$ to be constant.
Let $z=x+iy$, $\overline{z}=x-iy$.
So
\begin{align}f(z) &= (x-iy)^3 - 3(x-iy) \\&= (x-iy)(x^2 -i2xy +i^2y^2) - 3(x-iy)\\&= x^3 -i3x^y - 3xy^2 -iy^3 -3x + 3iy\end{align}
First off, this whole thing looks like a mess.
Am I supposed to continue with calculating $u(x,y)$, $v(x,y)$, then the partial derrivatives $u_x$,$u_y$,$v_x$,$v_y$ to check if
\begin{align}
u_x &= v_y \\
u_y &= -v_x \\
\end{align}
so the C-R are valid for every $x, y$?
Is this adequate to then say that the whole of $f(z)$ is differentiable for any complex $z$?
I'm sorry for this whole question but this exercise has me stumped.
A:
Instead of writing $f$ as a function $(x,y)\mapsto f(x+iy)$ write it as
$$q(z,\bar z):=(\bar z+1)^3-3\bar z=\bar z^3+3\bar z^2+1\ .$$
The given $f$ is complex differentiable at the points $z$ where
$${\partial q\over\partial\bar z}=3\bar z^2+6\bar z=0\ ,$$
i.e., at the points $z=0$ and $z=-2$.
(Treating the problem this way differs from $u_x=v_y$, $u_y=-v_x$ and solving for $(x,y)$ by mere linear algebra. There is no complex magic behind this.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Usage of "which" for connection
Here is a paragraph I wrote a couple days ago:
So if you are a person who can learn by himself/herself (which is a must-have trait if you are going to be a good programmer) then other tools that you have the control of the learning pace are way more useful than college.
I wonder if the usage of "which" here is correct or not? When a friend read it, he said that "which" must be "who" because I am talking about a person. But for me, the "which" relates to the "ability of being able to learn by yourself"
Maybe I'm thinking in my own language and this is creating a syntactic mistake?
A:
So if you are a person who can learn by himself/herself, which is a must-have trait if you are going to be a good programmer, then.....
The use of the relative pronoun "which" is correct in the sentence while the use of "who" is incorrect. you are referring to the entire previous clause, not a person, in the non-defining clause.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should I say something to an undergraduate research assistant who isn't really working full time?
I'm supervising an undergraduate research assistant this summer, who I hired for a full time position. There are several other full time research assistants in the lab, who work about 35-45 hours a week (specific hours of their choice).
This one student works about 25. He isn't unusually productive, either, and doesn't seem to be learning as much as the students who are actually working approximately full time. He isn't terribly behind, but I am sure he would make more progress on his project and have a better chance of finishing it by the end of the summer if he actually worked full time. (I designed the project so that it could reasonably be expected to be completed over the course of the summer by an undergrad working about 35-40 hours a week.)
Should I have a conversation with him about his working hours? If so, how to do it without sounding like a jerk?
A:
Should I have a conversation with him about his working hours?
Yes! He gets paid to do a job. He doesn't do the job. You need to talk to him, even though it's an uncomfortable situation. Also, you say in a comment:
Because the general culture in academia tends to be more like, "Work as many or as few hours as you want as long as you get your work done."
This is true, but you say that he does not get his job done. Frankly, if he only works like 25 hours, even if he would be supremely productive I would still talk to him about his work ethics if he puts in so much less hours than his peers... and if he is not it's all the more reason to make sure that he at least tries as hard as the others.
If you don't, the problem is going to be that sooner rather than later many of the 45-hours students are going to wonder why the heck they are actually not enjoying the summer. I have seen in my current group that various bad habits have a tendency to spread like wildfire if the students have the impression that not doing your job isn't in any way frowned upon anyway.
If so, how to do it without sounding like a jerk?
In private, without getting emotional or accusatory. Tell him that you have the impression that he works considerably below the amount that was agreed upon, and that you have to ask him to change this. Tell him that you have the impression that his project is not progressing fast enough, and what will happen if he can't get it done in time (you have some course of action in this case, right?). Be prepared that he may counter with some sort of attack against you. For instance, this is a classic in such situations: "Well, since you never have time for me, I don't know what to do half of the time anyway - so rather than just sit around I leave". Make sure that you have a good answer in this case.
A:
From the perspective of an undergrad student, I think you should address this issue. He might be unaware of the problem you are having with him since as you said, he is not behind in his work but you feel he could be more productive. He might even appreciate you telling him this if framed correctly, allowing him to pinpoint where he can improve and knowing that his advisor not only notices his performance but believes he can do better.
Mention that it is a paid full-time position and because of that there are expectations, despite the culture you mentioned in one of your comments. He might be able to get work done in the amount of hours a week he works, but increasing his hours not only ensures his work is done, it also shows his dedication. Also mention that the project is designed for someone to work 35 to 40 hours a week. He is not especially productive during his 25 hours a week, so it's not like he can get away with doing less than expected.
Sounding like a jerk would only be a problem, I think, if you don't explain your reasoning for talking to him about this. It might be best to address this in an informal setting outside of the lab, but that is more about where you personally think the conversation would be least confrontational. The way you approached the wording of the question definitely made you sound well intentioned and not jerk-ish in the slightest, so you shouldn't worry too much about your tone.
I would suggest asking him if he is only working 25 or so hours a week because he has other things going on in his personal life. It's a good place to start the conversation as it is coming from a place of concern and allows for you to get to your main problems with him as well. I'm assuming that the schedule is somewhat flexible, and if that is true, remind him of that and that you're willing to work with his schedule to some extent.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
codeigniter / database page not loading
I have a problem whith a database request : the webpage does not load at all.
public function get_mylist($user_id){
$this->db->select('*');
$this->db->from($this->_table);
$this->db->where('my', '1');
$this->db->where('user1', $user_id);
$this->db->or_where('user2', $user_id);
$query = $this->db->get()->result_array();
if($query!=NULL)
{
foreach($query as $row)
{
echo $row['user1'];
if($row['user2'] != $user_id)
{
$data[] = $row['user2'];
}
else if($row['user1'] != $user_id)
{
$data[] = $row['user1'];
}
}
return $data;
}
else return 0;
}
Do you have any idea ?
edit : in my log i have Fatal error: Allowed memory size bytes exhausted
So my loop must be wrong :/
A:
You need to consider how many rows in your DB table and how many bytes per row.
Do you have enough data in your table to reach the memory limit for your PHP configuration?
Also, check your logic in your SQL construction.
Specifically:
$this->db->where('my', '1');
$this->db->where('user1', $user_id);
$this->db->or_where('user2', $user_id);
This where clause is being interpreted as:
WHERE (`my` = 1 AND `user1` = $user_id) OR (`user2` = $user_id)
Is this what you intended, or do you need:
WHERE `my` = 1 AND (`user1` = $user_id OR `user2` = $user_id)
In MySQL, OR gets precedence over AND.
Finally, as a test, take out the code that parses the $data array and return the $row array and print it out using print_r($row) and make sure your query is pulling out the data that you expect.
Hopefully these ideas will help you diagnose the problem. Best of luck!
Note: To implement the alternative logic in SQL, you may do something like:
$this->db->where('my', '1');
$this->db->where("(`user1` = $user_id OR `user2` = $user_id)");
Pay attention to the opening/closing parentheses immediately to the inside of the
double quotes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Navbar on left of page, how to let content resize to match screen size?
So - I've got a website, and for navigation, I have a bar on the left in a div:
#menu {
float : left;
border-style : dashed none;
border-width : 1px;
font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
width : 190px;
margin-top : 20px;
}
And content on the right, also in a div:
#content {
padding-top : 10px;
margin-top : 20px;
position : relative;
width : 760px;
float : right;
}
And it's all contained in a div called page:
#page {
width : 100%;
margin-left : 30px;
margin-right : auto; ;
}
And it looks fine when the screen size matches the 960px width of the page, but if it doesn't, the content doesn't expand or shrink to fit. But if I put width:100% in the #content CSS, then the content pane appears at the bottom, since it can't fit to the right of it.
How can I fix it so the menu div will have that 190px width, and the content div will take whatever's left?
I am not using any other frameworks, so solutions which require jquery are of no use.
A:
You can use calc()(docs) in CSS for modern browsers:
#content {
padding-top : 10px;
margin-top : 20px;
position : relative;
width : calc(100% - 190px);
float : right;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Tweets returned by twitteR are shortened
I am using the twitteR package for R to collect some tweets. However, I noticed that the Tweet text returned by the searchTwitter function is not the complete tweet text, but abridged to equal exactly 140 characters with the rest of the text replaced by a link to the tweet on the web.
Using a tweet I found for an example:
require(twitteR)
require(ROAuth)
# authorize twitter with consmuer and access key/secret
setup_twitter_oauth(AAA, BBB, CCC, DDD) # actual secret codes go here...
# get sample tweet
tweet <- searchTwitter("When I was driving around earlier this afternoon I only saw two Hunters",
n=500,
since = "2017-11-04",
until = "2017-11-05",
retryOnRateLimit=5000)
# print tweet
tweet[[1]]
[1] "_TooCrazyFox_: When I was driving around earlier this afternoon I only saw two Hunters but it was during the midday break. I didn'… *SHORTENEDURL*"
# the *SHORTENEDURL* is actually a link that brings you to the tweet; stackoverflow didn't want me to a put shortened urls in here
# convert to data frame
df <- twListToDF(tweet)
# output text and ID
df$text
[1] "When I was driving around earlier this afternoon I only saw two Hunters but it was during the midday break. I didn'… *SHORTENEDURL*"
df$id
[1] "926943636641763328"
If I go to this tweet via my web browser, it is clear that twitteR shortened the text to 140 characters and included a link to the tweet containing the whole text.
I don't see any mention of this in the twitteR documentation. Is there any way to retain the entire tweet text during a search?
My assumption is that this is related to the change in Twitter character length as referenced here: https://developer.twitter.com/en/docs/tweets/tweet-updates (in the 'Compatibility mode JSON rendering'). This implies that I need to retrieve the full_text field, rather than the text field. However, this does not seem to be supplied by twitteR.
A:
The twitteR package is in process of being deprecated. You should use rtweet instead.
You can download rtweet from CRAN, but at the present time I recommend downloading the dev version from Github. The dev version will return the full text of tweets by default. It will also return the text of full, original text of retweeted or quoted statuses.
To install the most recent version of rtweet from Github, use the devtools package.
## install newest version of rtweet
if (!requireNamespace("devtools", quietly = TRUE)) {
install.packages("devtools")
}
devtools::install_github("mkearney/rtweet")
Once it's installed, load the rtweet package.
## load rtweet
library(rtweet)
rtweet has a dedicated package documentation website. It includes a vignette on obtaining and using Twitter API access tokens. If you follow the steps in the vignette, you only have to go through the authorization process once [per machine].
To search for tweets, use the search_tweets() function.
# get sample tweet
rt <- search_tweets(
"When I was driving around earlier this afternoon I only saw two Hunters",
n = 500
)
Print output (a tbl data frame).
> rt
# A tibble: 1 x 42
status_id created_at user_id screen_name
<chr> <dttm> <chr> <chr>
1 926943636641763328 2017-11-04 22:45:59 3652909394 _TooCrazyFox_
# ... with 38 more variables: text <chr>, source <chr>,
# reply_to_status_id <chr>, reply_to_user_id <chr>,
# reply_to_screen_name <chr>, is_quote <lgl>, is_retweet <lgl>,
# favorite_count <int>, retweet_count <int>, hashtags <list>, symbols <list>,
# urls_url <list>, urls_t.co <list>, urls_expanded_url <list>,
# media_url <list>, media_t.co <list>, media_expanded_url <list>,
# media_type <list>, ext_media_url <list>, ext_media_t.co <list>,
# ext_media_expanded_url <list>, ext_media_type <lgl>,
# mentions_user_id <list>, mentions_screen_name <list>, lang <chr>,
# quoted_status_id <chr>, quoted_text <chr>, retweet_status_id <chr>,
# retweet_text <chr>, place_url <chr>, place_name <chr>,
# place_full_name <chr>, place_type <chr>, country <chr>, country_code <chr>,
# geo_coords <list>, coords_coords <list>, bbox_coords <list>
Print tweet text (the full text).
> rt$text
[1] "When I was driving around earlier this afternoon I only saw two Hunters but it was during the midday break. I didn't have my camera otherwise I would have taken some photos of the standing corn fields in the snow. I'll do it later., maybe tomorrow.\n#harvest17"
To lookup Twitter statuses by ID, use the lookup_statuses() function.
## lookup tweet
tweet <- lookup_statuses("926943636641763328")
Print tweet text.
> tweet$text
[1] "When I was driving around earlier this afternoon I only saw two Hunters but it was during the midday break. I didn't have my camera otherwise I would have taken some photos of the standing corn fields in the snow. I'll do it later., maybe tomorrow.\n#harvest17"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I read the media-type attribute from xsl output using Java EE?
I using XSLT to transform XML to other content, in this case JSON. I set the MIME using the <xsl:output method="text" media-type="application/json" encoding="UTF-8"/> tag.
I transform XML into JSON using saxon9.
Transformer transformer = tFactory.newTransformer(new StreamSource(xslUrl));
ByteArrayInputStream xmlStream = new ByteArrayInputStream(xml.getBytes());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(baos);
transformer.transform(new StreamSource(xmlStream), new StreamResult(new OutputStreamWriter(dataOut)));
String output = baos.toString();
How can I also read the MIME as "application/json"?
A:
This is the method to call to grab the MIME from the xsl:output media_type.
String mime = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE);
You can then act accordingly, which in my case is to setContentType for the HttpServletResponse.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why not an `instance?` word?
Many object-aware scripting languages have an operator or function to test if an object is an instantiation of a given tuple or type. JavaScript has the instanceof operator, Python has an isinstance builtin as well as an issubclass builtin, etc.
But in Factor, all tuple classes and object types are given their own instance? word:
TUPLE: car speed ;
! autogenerated is the word car?, which tests if something is a car
TUPLE: boat weight ;
! autogenerated is the word boat?, which tests if something is a boat
100 boat boa boat? ! -> t
100 boat boa car? ! -> f
Boats are boats and cars are cars. Cars are not boats.
We could rephrase the last two lines like:
100 boat boa boat instance-of? ! -> t
100 boat boa car instance-of? ! -> f
Instead, every object in Factor has its own specialised instance? word. Is this just for brevity and readability, or is there an implementation reason?
Would one want to customise the instance? word on certain objects for some reason? We have generics for that...
A:
Your instance-of? would work most of the time:
: instance-of? ( obj cls -- ? ) [ class-of ] dip class<= ;
123 boat boa boat instance-of? .
t
123 boat boa tuple instance-of? .
t
123 fixnum instance-of? .
t
But it is not good enough for more complicated types:
QUALIFIED: math.primes
PREDICATE: even < integer 2 mod 0 = ;
PREDICATE: prime < integer math.primes:prime? ;
7 prime? .
t
6 even?
t
7 prime instance-of?
f
6 even instance-of? .
f
The other reason is optimization. Words like fixnum?, string? and array? that are used in performance sensitive code are much easier to make fast than a more general instance-of? word.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get the index of the biggest number in array?
I have this array:
float[] sizeEdge = new float[12,43,556,98];
Maybe my question will seem naive to some of ou but, Im a newer in .NET,
I need to get the array index of the biggest number.
How do I implement it?
Thank you in advance.
A:
float max = sizeEdge.Max();
int maxIndex = Array.IndexOf(sizeEdge, max);
Note this will iterate the array twice, and will throw an exception if the array is empty. If you need to handle these, a loop is probably cleaner. You could create an extension method:
public static int IndexOfMax<T>(this IEnumerable<T> seq) where T : IComparable<T>
{
if(! seq.Any()) return -1;
T max = seq.First();
int maxIdx = 0;
int idx = 1;
foreach(T item in seq.Skip(1))
{
if(max.CompareTo(item) < 0)
{
max = item;
maxIdx = idx;
}
++idx;
}
return maxIdx;
}
or a linq version:
public static int IndexOfMax<T>(this IEnumerable<T> seq) where T : IComparable<T>
{
return seq.Select((f, idx) => new { Val = f, Idx = idx })
.Aggregate(new { Max = default(T), MaxIndex = -1 }, (mp, fp) =>
{
return mp.MaxIndex == -1 || fp.Val.CompareTo(mp.Max) > 0 ? new { Max = fp.Val, MaxIndex = fp.Idx } : mp;
}).MaxIndex;
}
A:
You can use IEnumerable.Max() method like;
Returns the maximum value in a sequence of values.
float[] sizeEdge = new float[] { 12f, 43f, 556f, 98f };
int maxIndex = Array.IndexOf(sizeEdge, sizeEdge.Max());
Console.WriteLine(sizeEdge[maxIndex]);
Result will be;
556
Here a DEMO.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Select distinct on two tables
I'd like to select datas on tables without duplicates
For exemple
table1
data1; data2; data3; data4; data5
table2
data1; data2; data3
data1, data2, data3 are the same data type
table1
| data1 | data2 | data3 | data4 | data5 |
|----------|----------|----------|----------|----------|
| value1.1 | value2.1 | value3.1 | value4.1 | value5.1 |
table2
| data1 | data2 | data3 |
|----------|----------|----------|
| value1.1 | value2.1 | value3.1 |
| value1.2 | value2.2 | value3.2 |
| value1.3 | value2.3 | value3.3 |
I'd like to select data1, data2, data3 from my two tables with a distinct data1
| data1 | data2 | data3 |
|----------|----------|----------|
| value1.1 | value2.1 | value3.1 |
| value1.2 | value2.2 | value3.2 |
| value1.3 | value2.3 | value3.3 |
I'd like to have my result in only 3 columns
for exemple value1.1 is from table1 and value1.2 is from table2
A:
In a nutshell, you want the following:
SELECT data1, data2, data3
FROM table1
UNION /* Union without optional ALL will eliminate duplicates accross the two tables */
SELECT data1, data2, data3
FROM table2
However, there is still something you need to clarify. You state:
I'd like to select data1, data2, data3 from my two tables with a distinct data1
The problem is that you don't say what should happen if you have a duplicate data1 accross the two tables.
Suppose table1 has a row with values (1, A, B) and table2 has a row with values (1, X, Y). Which row should be included in the final output?
The above query will include both rows because they differ in columns: data2 and data3.
EDIT for comment:
if duplicate I'd like to have the table1 result
You still need UNION, but you need to control which rows are to be included in the union. NOTE: Because your query will now ensure there are no duplicates, you can use UNION ALL so the DMBS doens't waste processing time trying to eliminate duplicates that don't exist.
SELECT data1, data2, data3
FROM table1
UNION ALL
SELECT data1, data2, data3
FROM table2
WHERE NOT EXISTS (SELECT * FROM table1 WHERE table1.data1 = table2.data1)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Modelling a Poisson distribution with overdispersion
I have a data set that I'd expect to follow a Poisson distribution, but it is overdispersed by about 3-fold. At the present, I'm modelling this overdispersion using something like the following code in R.
## assuming a median value of 1500
med = 1500
rawdist = rpois(1000000,med)
oDdist = rawDist + ((rawDist-med)*3)
Visually, this seems to fit my empirical data very well. If I'm happy with the fit, is there any reason that I should be doing something more complex, like using a negative binomial distribution, as described here? (If so, any pointers or links on doing so would be much appreciated).
Oh, and I'm aware that this creates a slightly jagged distribution (due to the multiplication by three), but that shouldn't matter for my application.
Update: For the sake of anyone else who searches and finds this question, here's a simple R function to model an overdispersed poisson using a negative binomial distribution. Set d to the desired mean/variance ratio:
rpois.od<-function (n, lambda,d=1) {
if (d==1)
rpois(n, lambda)
else
rnbinom(n, size=(lambda/(d-1)), mu=lambda)
}
(via the R mailing list: https://stat.ethz.ch/pipermail/r-help/2002-June/022425.html)
A:
for overdispersed poisson, use the negative binomial, which allows you to parameterize the variance as a function of the mean precisely. rnbinom(), etc. in R.
A:
If your mean value for the Poisson is 1500, then you're very close to a normal distribution; you might try using that as an approximation and then modelling the mean and variance separately.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SOAP Request/Response based on Style/Use
I was wondering if someone could explain the differences in a SOAP request/response of a Web service with the following wsdl binding style/use:
Document/literal
RPC/literal
wrapped document style
Thanks in advance
A:
This article from IBM DeveloperWorks [Which style of WSDL should I use?] has an excellent explanation of the differences between these binding styles. In a nutshell, the only differences are the values of the SOAP binding "style" attribute ("rpc" or "document") in the WSDL file and the way the message arguments and return values are defined (and thus how they appear in the SOAP messages themselves):
[Note the reordering of items from the question to emphasize relationships]
RPC/literal - WSDL message element defines arguments and return value(s) of operations.
PROS: simple WSDL, operation name appears in SOAP message, WS-I compliant.
CONS: difficult to validate since arguments are defined in WSDL not XSD.
Document/literal - WSDL message parts are references to elements defined in XML Schema.
PROS: easily validated with XSD, WS-I compliant but allows breakage.
CONS: complicated WSDL, SOAP message does not contain operation name.
Document/literal wrapped (or "wrapped document style") - WSDL message input has single input and output parameters and input refers to XSD element with same local name as WSDL operation.
PROS: easily validated, SOAP message contains operation name, WS-I compliant.
CONS: most complicated WSDL (not an official style but a convention).
In my experience, #3 (Document/literal Wrapped) is very common in large enterprise projects because it is both Microsoft and OSS friendly and it is well suited for a top-down development model (e.g. WSDL/XSD first, then generate code artifacts). Microsoft invented it [1] and popular Java/OSS tools (Axis2, JAX-WS) support it explicitly.
The "real world" difference likely comes down to which styles are supported — and how well — by the tools of your choice.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Angular 5 - Bind a component selector with InnerHtml
I have a component1 selector that I called "app-component1".
@Component({
selector: 'app-component1',
templateUrl: './test-widget.component.html',
styleUrls: ['./test-widget.component.scss'] })
So to call the html of this component I usually use:
<app-component1></app-component1>
and it works perfectly fine.
Now from another component2 I have the following variable:
variableToBind = "<app-component1></app-component1>";
And In the html of component 2 I used the following:
<div [innerHtml]="varibableToBind"></div>
The html code binding isn't working. Is is possible to help me understand why and maybe help me find another alternative?
A:
Thanks Everyone for the suggestions, I actually just find the answer to this:
This can't work because innerHtml is rendered AFTER Angular's compiled the templates. That means that it doesn't understand your selectors at this point of time.
If you guys want to load a component (or any content) dynamically, you should use *ngIf. It worked perfectly fine for me.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ignore undefined values that are passed in the query object parameter for Mongoose's Find function?
So:
Sound.find({
what: req.query.what,
where: req.query.where,
date: req.query.date,
hour: req.query.hour}, function(err, varToStoreResult, count) {
//stuff
});
Say that only req.query.what has an actual value, "yes" for example, while the rest (req.query.where, req.query.date, etc.) are all undefined/empty. If I leave this code as is, it would look for docs which have what = req.query.what AND where = req.query.where, etc. but I would only want it to find docs which have their what value = to req.query.what, since the other fields are undefined/empty.
A:
You have to filter your res.query object from undefined/empty values first, and then pass it to find function. If you have just a couple of properties, you can use if statement:
const query = req.query;
const conditions = {};
if (query.what) {
conditions.what = query.what;
}
if (query.where) {
conditions.where = query.where;
}
....
Sound.find(conditions, function () {});
Or if there is a lot of properties you can iterate over them:
const query = req.query;
const conditions = Object.keys(query)
.reduce((result, key) => {
if (query[key]) {
result[key] = query[key];
}
return result;
}, {});
Sound.find(conditions, function () {});
Also, I would not advise to remove properties from the actual res.query object - delete res.query.what - because you won't be able to use it in another middleware if you would like to.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
play mp3 files at designated duration
I'm trying to make an app that can play mp3 files at designated duration through MediaPlayer
for example:
Start Time: 00:42
End Time: 01:23
my question is:
-is it possible to designate the start and end time via textview at MM:SS format?
Thanks!!
A:
Yes after initiating the MediaPlayer and loading the file , you can pause or stop the player after using specific time
while(mPlayer.isPlaying()) {
if(mPlayer.getCurrentPosition() > 7254 && mPlayer.getCurrentPosition() < 7410 ){
labelTxt.setText("Stop: " + mPlayer.getCurrentPosition() );
mPlayer.stop();
break;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Receive UDP broadcast packets across subnetworks the way wireshark can do it
I have an application on the PC that should get some UDP broadcast messages from a device on the local network.
The device periodically sends UDP broadcast messages to its subnetwork and the application should be able to receive these broadcasts. When the PC and the device are in the same subnetwork there is no problem receiving those messages.
However, when I place the device and the PC in different subnetworks then I can no longer receive the device's broadcasts in the PC application, but I can see them in wireshark.
Scenario 1
So if I have:
the PC at IP 10.0.100.100 with a subnet mask of 255.255.0.0
the device A at IP 10.0.254.83 with a subnet mask of 255.255.255.0
this proof-of-concept PC application:
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <assert.h>
#pragma comment(lib, "Ws2_32.lib")
int main()
{
WSADATA wsaData;
int iResult;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
sockaddr_in si_me, si_other;
int s;
assert((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1);
int port = 32002;
BOOL broadcast = TRUE;
setsockopt(s, SOL_SOCKET, SO_BROADCAST,
(char*)&broadcast, sizeof(broadcast));
memset(&si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(port);
si_me.sin_addr.s_addr = INADDR_ANY;
assert(bind(s, (sockaddr *)&si_me, sizeof(sockaddr)) != -1);
while (1)
{
char buf[10000];
memset(buf, 0, 10000);
int slen = sizeof(sockaddr);
recvfrom(s, buf, sizeof(buf)-1, 0, (sockaddr *)&si_other, &slen);
char *ip = inet_ntoa(si_other.sin_addr);
printf("%s: %s\n", ip, buf);
}
}
Then I don't receive the broadcast messages from the device.
Scenario 2
However if I have a device B at IP 10.0.255.222 with subnet mask of 255.255.0.0 I can receive the messages, even though the PC is still in another subnetwork.
Scenario 3
If I move the PC at 10.0.254.100 with subnet mask 255.255.255.0 then I can communicate with the device A, but then I cannot see the messages from the device B at 10.0.255.222.
The thing that confuses me more is that in both cases Wireshark can capture the packets.
Why can't my application see the packets from device A and why wireshark can (in the first scenario)? What can I do similar to wireshark so I can see those packets?
What's the explanation behind scenario 2 and 3?
Since in scenario 2 the device B is clearly in another subnetwork, but the loss of communication happens only in scenario 3
What should I read to get a better understanding of these issues?
PS: I don't think the problem comes from the UDP's unreliability.
PPS: I did try to disable "Capture packets in promiscuous mode", the result is the same, I can see the packets from the device A in Wireshark
A:
One thing is - Wireshark uses promiscuous mode - so it can read anything that comes on the switch port. This might include your own broadcasts, some other broadcasts and even some uni/multicasts which are not meant for you - provided the packet comes to that switch port. This is not the case with your program. Your program is trying to receive datagrams for the network broadast address only. Now the explanation below would help.
I think you are confusing network Addresses and broadcast domains. Here is what is happening in your case
Scenario 1.
PC - 10.0.100.100 netmask 255.255.0.0 so the broadcast address is 10.0.255.255, (In general anything that is 0 in netmask - if that is set to all 1s becomes a broadcast address. )
So anything sent to this broadcast address will be received by your App.
Device A 10.0.254.83 netmask 255.255.255.0. So the broadcast address is 10.0.254.255. Note it is different from the broadcast address of PC and hence - you cannot receive them.
So don't get confused by outwardly looking identical network addresses.
Scenario 2
Device B - 10.0.255.222 netmask 255.255.0.0. So The broadcast address is 10.0.255.255. This is same as your PC's address in scenario 1 above and hence can receive the datagrams (without being in promiscuous mode). (The 255.222 part might look like a different network, but it is not because the netmask is 16 byte 255.255.0.0.
Scenario 3
PC : 10.0.254.100 netmask 255.255.255.0 so the broadcast address for the network is 10.0.254.255 - which is same as Device A's broadcast address (10.0.254.255) in Scenario 1, but not same as broadcast address of Device B (10.0.255.255) in Scenario 2 and hence the expected outcome.
In your scenario - the Device A's network is a subnet of Device B and PC's network and broadcasts are restricted to subnets only. When you move PC into the subnet you receive the broadcast of the Subnet (Senario 3).
Edit:
Explanation - why you can see subnetwork broadcasts in wireshark and why not in your application is - What you see in wireshark is whatever is 'received by your network card'. Since all broadcasts do have a destination mac of ff:ff:ff:ff:ff your card is going to receive it, but your OS stack is going to drop them as the network level address is not the network level broadcast. And Layer 2 broadcasts will be received even without promiscuous mode.
Hope that helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
For Loop with sed textfile
I tried this out, but it is not working. I was wondering if you could help me out:
I have several text files in a folder and I want to copy the lines 111 to 734 from file1 in that folder and add to the other textfiles in that folder.
sed -n 111,734p file1>patch
for i in *;
do sed -i 110rpatch;
done
What am I doing wrong??
thanks
A:
I would rewrite this as
sed -n 111,734p file1>patch
for i in *; do
case "$i" in patch) continue ;; esac
sed -i '110rpatch' "$i"
done
As the patch file is in the same dir as all the $i files, you need the case/continue test to skip processing the patch file.
IHTH
|
{
"pile_set_name": "StackExchange"
}
|
Q:
change value A to B, no matter which column it is in
Single UPDATE working:
UPDATE users SET email=@newemail WHERE email=@oldemail
(1 Zeile(n) betroffen)
Double UPDATE not working:
UPDATE users SET email=@newemail WHERE email=@oldemail, alternateEmail=@newemail WHERE alternateEmail=@oldEmail
Meldung 102, Ebene 15, Status 1, Zeile 1
Incorrect syntax near ','.
How would I do this in a single statement (even if I have N columns to check)?
To clarify: If I have the table
email alternateEmail
[email protected] [email protected]
[email protected] [email protected]
and I set @oldemail='[email protected]', @newemail='[email protected]', the resulting table should be
email alternateEmail
[email protected] [email protected]
[email protected] [email protected]
I know I could do it in 2 (or N) statements:
UPDATE users SET email=@newemail WHERE email=@oldemail
UPDATE users SET alternateEmail=@newemail WHERE alternateEmail=@oldEmail
but could I do it in one statement?
A:
You can do it like this:
UPDATE users SET
email = case
when email = @oldemail then @newemail
else email
end,
alternateEmail = case
when alternateEmail = @oldemail then @newemail
else alternateEmail
end
where
email = @oldemail
or alternateEmail = @oldemail
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Staring using Spring to build a java application
I would build a Java application and in the same time learn Spring framework. This application is not too complicated. It simply receives datas from the users and save them into databases for a future retrieving from the users. Now I would use Spring but I don't know if it is a good idea. What do you suggest me?
A:
Well for this small application no one will recommend you to use Spring as that means cutting a lemon with sword, but learning a new platform/framework is always a good idea, since you want to learn Spring so its always better to learn something with some example or application development so i will suggest you to go ahead with your quest.
Spring in-itself is a vast sea and you firstly need to decided which all parts you want to learn, as a starting point i will recommend you to go ahead learn Dependency Injection principle of Spring and later you can start exploring other aspects of Spring.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I extract text at even positions?
I am extracting a page with Nokogiri which returns a Nokogiri::XML::NodeSet. From this, I would like to extract only the text from even nodes.
doc.search("h2 a").class #=> Nokogiri::XML::NodeSet
doc.search("h2 a").count #=> returns 148
I am interested in 0,2,4,8, etc.:
doc.search("h2 a")[0].text #=> the one I wanted.
doc.search("h2 a")[2].text #=> the one I wanted.
A:
Try the below :
doc.search("h2 a").map.with_index(0) do |i,nd|
i.text if nd.even?
end.compact
A:
Maybe you want every even-positioned a node:
doc.search("h2 a:nth-child(even)")
or perhaps you are looking for every other node over all:
doc.search("h2 a").select.with_index{|a, i| i.even?}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get the bounding box of a rotated object
I want to get the exact rotated bounding box of an object after rotate it to make a collision detection between two objects.
i use setFromObject of the THREE.Box3 but if the object rotated the bounding box after rotation does not rotate with the object.
the question which is asked before does not has an answer so i asked again to have one and i did.
A:
Bounding box in Three.js seems axis aligned: http://3dengine.org/i/bounding.jpg.
Maybe you can use a BoxGeometry and make the collision building a plane equation with the faces normal and check points front or back side.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to backup PhpStorm project Context?
I like so much the Context feature of PhpStorm, localized in Tools > Tasks & Contexts > Save Context or Load Context
When I have a new computer, I can import all PhpStorm settings, but how to can I backup Context to my other computer?
A:
Such data is stored in separate .zip files on per project basis (tasks and contexts separately -- 2 files per project).
On Windows 7 for PhpStorm v10 they will be located in C:\Users\USERNAME\.WebIde100\config\tasks folder.
For another OS/IDE version please check this document.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Implementing selection sort using a list C++
I want to implement selection sort to sort the departure time of flights but it doesn't print me the result (And I am not sure if it will be correct). Sorry for the long and silly question, I am new in programming. Here is the code that I made by now:
// Sort class
class Sort
{
protected:
// number of comparisons performed in sort function
unsigned long num_cmps;
public:
// main entry point
virtual void sort(std::vector<Flight>& data) = 0;
// returns false if not sorted true otherwise
bool testIfSorted(const std::vector<Flight>& data);
// returns number of comparisons
unsigned long getNumCmps();
// resets the number of comparisons
void resetNumCmps();
};
// SelectionSort class
class SelectionSort : public Sort
{
public:
// main entry point
void sort(std::vector<Flight>& data);
};
// BubbleSort class
class BubbleSort : public Sort
{
public:
// main entry point
void sort(std::vector<Flight>& data);
};
#include "Sort.h"
using namespace std;
unsigned long Sort::getNumCmps()
{
return num_cmps;
}
void Sort::resetNumCmps()
{
num_cmps = 0;
}
void Menu::selection_sort(){
system("cls");
ifstream in("inputFileExample.txt");
if (!in)
{
cerr << "ERROR: wrong input file name!";
exit(-1);
}
SelectionSort();
}
void SelectionSort::sort(std::vector<Flight>& data){
for (int i = 0; i < (num_cmps - 1); i++)
{
int smallest = i;
for(int j = (i+1); j<num_cmps; j++)
{
if(data[j] < data[smallest])
{
smallest = j;
}
}
num_cmps++;
cout << num_cmps;
}
}
A:
This statement
SelectionSort();
creates a temporary object of type SelectionSort, and that's it.
You don't actually read anything from the file, you don't have a vector to sort, you don't call the sorting function.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to remove a team from Slack
Is it possible to remove a team from the Slack app for Android, without uninstalling and reinstalling the app?
A:
Yes.
Connect to the team you wish to remove and tap the vertical elipsis menu. Go to "Settings". Scroll down until you see "Sign out of " in red. Tap it and confirm.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C# : Some questions about a method which allows to display a label for a specific time
I searched in google for a method which allows me to display a label for a specific time and I found this :
public void InfoLabel(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(InfoLabel), new object[] { value });
return;
}
barStaticItem3.Caption = value;
if (!String.IsNullOrEmpty(value))
{
System.Timers.Timer timer = new System.Timers.Timer(6000) { Enabled = true };
timer.Elapsed += (sender, args) =>
{
this.InfoLabel(string.Empty);
timer.Dispose();
};
}
}
I really can't understand this method specially :
-Why we used : InvokeRequired ?
-What this method for : this.Invoke() ?
-What this is for :new Action<string>(InfoLabel) ?
-Why we used that sign : => ?
A:
All of the invoke related stuff is because the person who write that code used the wrong Timer (there are quite a few in the language). You should be using System.Windows.Forms.Timer here.
public void InfoLabel(string value)
{
System.Windows.Forms.Timer timer = new Timer();
timer.Interval = 1000;//or whatever the time should be.
timer.Tick += (sender, args) =>
{
label1.Text = value;
timer.Stop();
};
timer.Start();
}
The forms timer will have code inside of it's own implementation that does something similar to the code that is in your sample (although I find it to be a particularly messy way of doing so). It will ensure that the Tick event runs in the UI thread so that you don't need to add in all of that boilerplate code.
The => is a lambda expression. It's a way of defining a new anonymous method that takes two parameters sender and args.
You could also use Tasks to solve this problem, rather than using timers:
public void InfoLabel2(string value)
{
Task.Factory.StartNew(() => Thread.Sleep(1000)) //could use Task.Delay if you have 4.5
.ContinueWith(task => label1.Text = value
, CancellationToken.None
, TaskContinuationOptions.None
, TaskScheduler.FromCurrentSynchronizationContext());
}
A:
Many questions!
InvokeRequired is due to the multi-threaded nature of applications. A UI based application has a UI thread on which all the updates for the user interface are done. Updating a member of the control from a non-UI thread will throw a cross thread exception, using Invoke will marshal the update to the UI thread - which is legal.
The Action<string> is a delegate for a method, it will call the InfoLabel method when the delegate is called with the passed in arguments - e.g. action.Invoke("someString"). The => is a lambda expression which is used to create an anonymous method (e.g. a method with no name) which will be run instead of pointing to a named method
A:
InvokeRequired checks to see if the code is currently running on the thread that created the form. If it's not then the function needs to invoke itself on the thread that DID create the form as WinForms code is not threadsafe.
Action is a delegate type that describes a function that takes a string (see the InfoLabel funcion? That's what it's referring to).
this.Invoke(new Action<string>(InfoLabel), new object[] { value });
The above is saying. Please create a new delegate of type Action from the function InfoLabel and invoke it using the thread that created this. When you invoke it pass the object 'value' to it. ie call InfoLabel(value) on the thread that created the form. Notice that it returns from the function directly afterwards so none of the 'meat' of the function is run on the wrong thread (we are on the wrong thread at this point, otherwise InvokeRequired would not have been true). When the function is run again by Invoke it will be on the right thread and InvokeRequired will be false so this bit of code will not be run.
timer.Elapsed += (sender, args) =>
{
this.InfoLabel(string.Empty);
timer.Dispose();
};
The above code is assigning an anonymous method to the Elapsed event of the timer. The first bit (sender, args) is describing the parameters of the method, then => is saying 'here comes the method', followed by a block of code (all the stuff inside the brackets).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
float left right bottom
I set the parent div to relative, and the others to absolute and 50% width, but even jsfiddle shows that it's not working. What am I missing?
http://jsfiddle.net/kagawa_leah/3gcV9/1/
html:
<div class="border">
<div class="left">
<p>LEFT Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. </p>
</div> <!--end left-->
<div class="right">
<p> RIGHT Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. </p>
</div> <!--end right-->
</div> <!--end border -->
css:
.border {
position: relative;
height: 100px;
background-color: #000000;
}
.left {position: absolute;
width: 50%;
float:left;
text-align:left;
bottom: 4px;
background-color:red;
}
.right {position: absolute;
width: 50%;
float:right; text-align:right;
bottom: 4px;
background-color: blue;
}
A:
You can’t float absolute positioned elements. You probably just want to set right/left on each element. Here is an example fiddle: http://jsfiddle.net/ByVGf/1/
.border {
position: relative;
height: 100px;
background-color: #000000;
}
.left {position: absolute;
width: 50%;
left: 0
text-align:left;
bottom: 4px;
background-color:red;
}
.right {position: absolute;
width: 50%;
right: 0;
text-align:right;
bottom: 4px;
background-color: blue;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
To play Mists of Pandaria, will I need to buy all other World of Warcraft expansions?
Possible Duplicate:
Do I need to buy all the released updates to begin playing WoW?
A new expansion seems a good place to step in, but to play Mists of Pandaria, will I have to buy every game in the WoW universe?
These include:
The main game
Burning Crusade
Wrath of the Lich King
Cataclysm
What would likely happen if I bought Mists of Pandaria and then tried to log in (with a subscription on my account)?
A:
Short answer: Yes.
Long Answer: Yes, you have to purchase all of the expansions prior to the most recent expansion in order to play the most recent expansion. The simplest reasoning for this is that each expansion also includes a level range. You cannot level to 90 without first leveling to 60, then to 70, then to 80, and then to 85.
It's worth mentioning that The Burning Crusade and Classic (vanilla) are packaged together, so they cannot be purchased separately. At regular price, The Battle Chest (the combination of TBC and Classic, including a free month of play) is $19.99 USD, Wrath of the Lich King is $19.99 USD, and Cataclysm is $39.99 USD. You can also play for free up to level 20 with the Starter Edition.
Also, there is a discount if you purchase all of these at once. However, I believe that you have to create a Battle.net account (don't worry, it's free) and then buy the game from Battle.net, attaching it directly to your account.
A:
You need all the games in order to play this new expansion. It sucks but in order to progress to level 90 you will need all of the expansions.
You will need The Burning Crusade, Wrath of the Lich King, Cataclysm and the Main game in order to do this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I programmatically silence Rake tasks?
I have a Rake task that depends on Rake::PackageTask. I need the output from my own task in our logs but I don't need 1000+ lines of output from the package task.
Is there any way I can silence Rake::PackageTask? Or is there a way I can programmatically silence any task, without having to specify rake --silent?
A:
You can redirect logs to /dev/null before calling the silent rake task. And then restore them back..
dev_null = Logger.new("/dev/null")
Rails.logger = dev_null
ActiveRecord::Base.logger = dev_null
Rake::Task['blah_blak'].invoke
#then restore the logger back
|
{
"pile_set_name": "StackExchange"
}
|
Q:
macro output doesn't work
I'm learning c++,The macro behavior not as expected.
1 #include<cstdlib>
2 #include<iostream>
3 #include<cstring>
4 #define die(x) std::cout << x << std::endl ; exit(-1)
5 const char *help = "Usage: coffee --help --version";
6 const char *version = "alpha";
7 int main(int argc,char **argv)
8 {
9 if(argc<2||!strcmp(argv[1],"--help"))
10 die(help);
11 if(!strcmp(argv[1],"--version"))
12 die(version);
13
14 return 0;
15
16 }
g++ -o sample ./*
./sample --help
Output:Usage: coffee --help --version
./sample --version
Output:
I'm confused why --version didn't output string alpha.
A:
When std::cout << x << std::endl ; exit(-1) is expanded by the macro preoprocessor in these two lines
9 if(argc<2||!strcmp(argv[1],"--help"))
10 die(help);
the resulting code is:
if(argc<2||!strcmp(argv[1],"--help"))
std::cout << help << std::endl;
exit(-1);
Which is probably not what you wanted;
The common trick for "multistatement macros" is to use do { ... } while(0) around the statements you want to have in a macro.
You can use gcc -E or cl -E to get the output from the C preprocessor, so you can see what the compiler ACTUALLY sees.
Edit: I should point out that I personnaly would prefer, in this case, a "die(msg) function" rather than fixing up the macro. Then you can, for example, set a breakpoing in die() and find out how you got there when something isn't working right! You can't set a breakoint in a macro.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
claim a lost watch
If someone claimed a lost watch, is it necessarily true that he took it? Or did he simply ask for it? The word "claim" seems to have multiple definitions.
The police said John claimed the watch.
I'd appreciate your help.
A:
The word claim has three basic connotations. The first is to make an assertion of the truth of a statement:
&lbrack1&rbrack He claimed he saw a ghost
The second and third are declarations of ownership. Of these, the former states a demand of ownership based on right;
&lbrack2a&rbrack He claimed the watch was his because his father had bequeathed it to him.
the latter asserts both ownership and actual possession:
&lbrack2b&rbrack He landed on the island and claimed it for the King.
Without knowing more about the procedures for lost or stolen property, you can't tell whether your hypothetical visitor to the police was allowed to walk off with the watch (2b) or whether he had to be satisfied with merely filing a claim for it (2a).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Oracle : Get average count for last 30 business days
Oracle version 11g.
My table has records similar to these.
calendar_date ID record_count
25-OCT-2017 1 20
25-OCT-2017 2 40
25-OCT-2017 3 60
24-OCT-2017 1 70
24-OCT-2017 2 50
24-OCT-2017 3 10
20-OCT-2017 1 35
20-OCT-2017 2 60
20-OCT-2017 3 90
18-OCT-2017 1 80
18-OCT-2017 2 50
18-OCT-2017 3 45
i.e for each ID, there is one record count for a given calendar day. The days are NOT continuous, i.e there may be missing records for weekends/holidays etc. On such days, there will not be records available for any ID. However on working days there are entries available for each ID .
I need to get the average record count for last 30 business days for each id
I want an output like this. ( Don't go by the values. It is just a sample )
ID avg_count_last_30
1 150
2 130
3 110
I am trying to figure out the most efficient way to do this. I thought of using RANGE BETWEEN , ROWS BETWEEN etc , but unsure it would work.
Off course a query like this won't help as there are holidays in between.
select id, AVG(record_count) FROM mytable
where calendar_date between SYSDATE - 30 and SYSDATE - 1
group by id;
what I need is something like
select id , AVG(record_count) FROM mytable
where calendar_date between last_30th_business_day and last_business_day
group by id;
last_30th_business_day will be count(DISTINCT business_days ) starting from most recent business day going backwards till I count 30.
last_business_day will be most recent business day
Would like to know experts opinion on this and best approach.
A:
Based on your comment try this one:
WITH mytable (calendar_date, ID, record_count) AS (
SELECT TO_DATE('25-10-2017', 'DD-MM-YYYY'), 1, 20 FROM dual UNION ALL
SELECT TO_DATE('25-10-2017', 'DD-MM-YYYY'), 2, 40 FROM dual UNION ALL
SELECT TO_DATE('25-10-2017', 'DD-MM-YYYY'), 3, 60 FROM dual UNION ALL
SELECT TO_DATE('24-10-2017', 'DD-MM-YYYY'), 1, 70 FROM dual UNION ALL
SELECT TO_DATE('24-10-2017', 'DD-MM-YYYY'), 2, 50 FROM dual UNION ALL
SELECT TO_DATE('24-10-2017', 'DD-MM-YYYY'), 3, 10 FROM dual UNION ALL
SELECT TO_DATE('20-10-2017', 'DD-MM-YYYY'), 1, 35 FROM dual UNION ALL
SELECT TO_DATE('20-10-2017', 'DD-MM-YYYY'), 2, 60 FROM dual UNION ALL
SELECT TO_DATE('20-10-2017', 'DD-MM-YYYY'), 3, 90 FROM dual UNION ALL
SELECT TO_DATE('18-10-2017', 'DD-MM-YYYY'), 1, 80 FROM dual UNION ALL
SELECT TO_DATE('18-10-2017', 'DD-MM-YYYY'), 2, 50 FROM dual UNION ALL
SELECT TO_DATE('18-10-2017', 'DD-MM-YYYY'), 3, 45 FROM dual),
t AS (
SELECT calendar_date, ID, record_count,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY calendar_date desc) AS RN
FROM mytable)
SELECT ID, AVG(RECORD_COUNT)
FROM t
WHERE rn <= 30
group by ID;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
regular functions over non-reduced curve
We know that the regular functions over a connected compact complex manifold are constants. I wonder that if this is true for non-reduced compact complex space. More precise, Let $X$ be a complex compact manifold of dimension three and $I\subset \mathcal O_X$ an ideal such that the complex subspace $C$ defined by $I$ is of dimension one. Then, I want to know if we have
$$H^0(C,\mathcal O_X/I)=\mathbb C.$$
If not, how about we suppose that $H^1(X,\mathcal O_X)=H^1(C,\mathcal O_X/I)=0$?
Now what in my mind is an example as following. Let $X=\mathbb P^3$ and $C$ is the curve defined by $x_2^2=x_3=0$ where $[x_0:x_1:x_2:x_3]$ is the coordinate on $\mathbb P^3$. Then by adjunction formula, we can show that $H^1(C,\mathcal O_C)=1$, and by a explicit calculation, we can also show that $H^0(C,\mathcal O_C)=0$. In general, we consider the following short exact sequence,
$$0\rightarrow I\rightarrow \mathcal O_X\rightarrow \mathcal O_C\rightarrow 0.$$
Under the assumption $H^1(X,\mathcal O_X)=H^1(C,\mathcal O_C)=0$. Then $H^0(C,\mathcal O_C)=\mathbb C$ is equivalent to show that $H^1(X,I)=0$. But I do not know how to show this or how to construct a counterexample.
Thank you very much for your answer or any comments.
A:
If you take a complete intersection curve like yours ($x_2^2=x_3=0$), then by Koszul resolution, you can easily show that $H^1(I)=0$. But, in general, there are non-reduced curves (connected) in 3-space which have $H^0(\mathcal{O}_C)\neq 0$.
Here is a standard construction. For definiteness, take a line $L$ in 3-space. Then $I_L/I_L^2=\mathcal{O}_L(-1)^2$ and so we can find a surjection to $\mathcal{O}_L(k)$ for any $k\geq -1$ from this rank two vector bundle. The push-out using $0\to I_L/I_L^2\to \mathcal{O}_{\mathbb{P}^3}/I_L^2\to \mathcal{O}_L\to 0$ gives a subscheme (sometimes called a ribbon) which will have $H^0=H^0(\mathcal{O}_L)\oplus H^0(\mathcal{O}_L(k))$ and thus if you take $k\geq 0$, you get such examples.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does adding the suffix "ality" to a noun change its meaning?
I thought that -ality was used to turn an adjective into a noun : bestial to beastiality, final to finality.
But I see that some people add it onto the end of nouns : criminal to criminality, position to positionality.
What do you think?
A:
There are three parts to the answer:
PART I
We are not adding '-ality', but '-ity'.
Bestial + -ity = Bestiality
Criminal + -ity = Criminality
Final + -ity = Finality
Positional + -ity = Positionality
Functional + -ity = Functionality
PART II
In each of these examples, we are adding -ity to an adjective and turning it into a noun. Criminal can be noun as well as an adjective. For example, "criminal offence", so can be positional, e.g. 'positional reference'.
So your original hypothesis is correct (with slight adjustment to the suffix). We add -ity to the adjectives ending into -al to form a noun.
PART III
As to your question about the change in meaning. The change is that now you are talking about the phoenomenon of the quality. Finality is a state or phenomenon of the quality 'being final'.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Bitlocker on a laptop without carrying around recovery key
We have a rule in my company that all PC drives must be encrypted with BitLocker, including laptops.
My own Windows 8 laptop has a tendency to hang at shutdown, black screen but the computer never stops (once waited for 30 minutes to no avail). I'd say it happens 25% of the time on average. The problem is, I then have to stop it manually and when it reboots I get the "Bitlocker blue screen of death" asking me to enter the recovery key.
If I have the key at hand everything then goes back on track, but I'm carrying this computer around everywhere I go, including places I don't have access to my company's network where the key is stored.
I understand the recovery key can be used to decrypt the drive, so I imagine it is not safe to have it with me all the time. I'm tempted to store it on my cell phone though, because if the laptop fails on me in the middle of nowhere/abroad/at a client's/on a train I have no other choice except calling someone at the office to give with the key - which I don't know if they'll be willing to do.
How can I deal with that problem ? Is Bitlocker really a reliable option for a mobile device considering potential hardware failings (especially in an SSD drive) ?
A:
What kind of attack are you trying to protect yourself from?
Assuming your only concern is that the data on your lost/stolen laptop will not be readable, then it is OK to carry the recovery key with you. Generally people are very good at securing their wallets, it should be "safe" to keep it on a piece of paper in your wallet.
If you're concerned about being directly threatened to divulge the key then it's obviously a much bigger risk to be carrying the recovery key around.
From a usability perspective though, I would not want to go through the pain of entering the key repeatedly (you mention it's 25% of the time!) Your best move is to solve whatever problem is hanging your laptop on shutdown.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
java thread hanging causing other threads to hang (continued)
I managed to generate thread dump when my test case hanging. However, it doesn't seemed to be a deadlock, a race condition or resource contention. But it definitedly hung while running the test case in my loading testing tool with 3 virtual users. Anyone can point me to the right direction here? Cheers
"Servlet.Engine.Transports : 387" daemon prio=5 tid=0x15386f8 nid=0x943 waiting on monitor [0xb4781000..0xb4781a00]
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:415)
at com.ibm.ws.util.BoundedBuffer.take(BoundedBuffer.java:161)
at com.ibm.ws.util.ThreadPool.getTask(ThreadPool.java:422)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:669)
"Servlet.Engine.Transports : 385" daemon prio=5 tid=0x51e898 nid=0x93e waiting on monitor [0xb3281000..0xb3281a00]
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:415)
at com.ibm.ws.util.BoundedBuffer.take(BoundedBuffer.java:161)
at com.ibm.ws.util.ThreadPool.getTask(ThreadPool.java:422)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:669)
"Servlet.Engine.Transports : 384" daemon prio=5 tid=0x464760 nid=0x93d waiting on monitor [0xb3381000..0xb3381a00]
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:415)
at com.ibm.ws.util.BoundedBuffer.take(BoundedBuffer.java:161)
at com.ibm.ws.util.ThreadPool.getTask(ThreadPool.java:422)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:669)
"Servlet.Engine.Transports : 382" daemon prio=5 tid=0x1141de8 nid=0x8a0 waiting on monitor [0xb3581000..0xb3581a00]
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:415)
at com.ibm.ws.util.BoundedBuffer.take(BoundedBuffer.java:161)
at com.ibm.ws.util.ThreadPool.getTask(ThreadPool.java:422)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:669)
"Servlet.Engine.Transports : 380" daemon prio=5 tid=0x1151ad8 nid=0x6b5 waiting on monitor [0xb3e81000..0xb3e81a00]
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:415)
at com.ibm.ws.util.BoundedBuffer.take(BoundedBuffer.java:161)
at com.ibm.ws.util.ThreadPool.getTask(ThreadPool.java:422)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:669)
"Servlet.Engine.Transports : 366" daemon prio=5 tid=0x1a1d110 nid=0x3fb waiting on monitor [0xb4b81000..0xb4b81a00]
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:415)
at com.ibm.ws.util.BoundedBuffer.take(BoundedBuffer.java:161)
at com.ibm.ws.util.ThreadPool.getTask(ThreadPool.java:422)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:669)
"Servlet.Engine.Transports : 365" daemon prio=5 tid=0x4e8bd8 nid=0x3fa waiting on monitor [0xb6281000..0xb6281a00]
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:415)
at com.ibm.ws.util.BoundedBuffer.take(BoundedBuffer.java:161)
at com.ibm.ws.util.ThreadPool.getTask(ThreadPool.java:422)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:669)
"Servlet.Engine.Transports : 362" daemon prio=5 tid=0x17055b0 nid=0x3f7 waiting on monitor [0xb3481000..0xb3481a00]
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:415)
at com.ibm.ws.util.BoundedBuffer.take(BoundedBuffer.java:161)
at com.ibm.ws.util.ThreadPool.getTask(ThreadPool.java:422)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:669)
"Servlet.Engine.Transports : 356" daemon prio=5 tid=0x1ddbae0 nid=0x3f1 waiting on monitor [0xb9c01000..0xb9c01a00]
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:415)
at com.ibm.ws.util.BoundedBuffer.take(BoundedBuffer.java:161)
at com.ibm.ws.util.ThreadPool.getTask(ThreadPool.java:422)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:669)
"Servlet.Engine.Transports : 299" daemon prio=5 tid=0x2519028 nid=0x3b5 waiting on monitor [0xb6001000..0xb6001a00]
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:415)
at com.ibm.ws.util.BoundedBuffer.take(BoundedBuffer.java:161)
at com.ibm.ws.util.ThreadPool.getTask(ThreadPool.java:422)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:669)
A:
Unless you have your own com.ibm.* class running, it looks like all these threads are normal "I'm waiting for something to do" threads of an application server. Are you sure this is the full thread dump? It appears that your test has probably executed and finished and the container is waiting for something to do...?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why am I seeing CheckMX depreciated warning?
I am seeing the following warning in symfony's profiler:
User Deprecated: The "checkMX" option is deprecated since Symfony 4.2.
I would like to know how to get rid of the warning, thanks.
I am not clear where this is coming from? In the trace it points to the following code in one of my repositories.
/**
* @return Ride[] Returns an array of Ride objects
*/
public function findRidesByYear($year)
{
return $this->createQueryBuilder('r')
->andWhere('r.date >= :year')
->setParameter('year', $year)
->orderBy('r.date', 'ASC')
->getQuery()
->getResult()
;
}
Specifically it is highlighting the getResult() function as shown in the screenshot:
A:
This a deprecation that was introduced in Symfony 4.2 on the @Assert\Email validation, which you are probably using. See: https://symfony.com/doc/current/reference/constraints/Email.html#checkmx
The reason for the deprecation are given in the docs:
This option is not reliable because it depends on the network conditions and some valid servers refuse to respond to those requests.
You can fix the deprecation by removing the option from the assertion usage, e.g. in your entities. Instead you can use the strict option that uses a different library egulias/email-validator to perform a strict validation for the email address.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Bootstrap css overrules my slidemenu's css
I've made my first slidemenu and everything seems fine except the
content in the menu itself. The slidemenu has pretty big spaces between each link and disabling the bootstrap stylesheet will make it looks like I want it to be.
Is there something i need to change in the Bootstrap.css?
How i want it to be
how it currently is with bootstrap.css active
@import url('https://fonts.googleapis.com/css?family=Alegreya+Sans:800');
body{
font-family: 'Alegreya Sans', sans-serif;
overflow-x: hidden;
}
.nav{
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
opacity: .9;
overflow-x: hidden;
padding-top: 60px;
transition: .7s;
}
.nav a {
display: block;
padding: 20px 30px;
font-size: 25px;
text-decoration: none;
color: #ccc;
}
.nav a:hover {
color: #fff;
transition: .4s;
}
.nav .close{
position: absolute;
top: 0;
right: 22px;
margin-left: 50px;
font-size: 30px;
}
.slide a{
color: #000;
font-size: 36px;
}
#sidemenu{
padding: 20px;
transition: margin-left .7s;
overflow: hidden;
width: 100%;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!--scripts-->
<script defer src="https://use.fontawesome.com/releases/v5.0.7/js/all.js">
</script>
<script>
function openSlideMenu() {
document.getElementById('menu').style.width = '250px';
document.getElementById('slidemenu').style.marginLeft= '250px';
}
function closeSlideMenu() {
document.getElementById('menu').style.width = '0px';
document.getElementById('slidemenu').style.marginLeft= '0px';
}
</script>
<!--css-->
<link rel="stylesheet" href="../css/Index.css">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Frontpage</title>
</head>
<body>
<div id="slidemenu">
<span class="slide">
<a href="#" onclick="openSlideMenu()">
<i class="fas fa-bars"></i>
</a>
</span>
<div id="menu" class="nav">
<a href="#" class="close" onclick="closeSlideMenu()">
<i class="fas fa-times"></i>
</a>
<!--Links slidemenu-->
<a href="#">home</a>
<a href="#">about</a>
<a href="#">services</a>
<a href="#">portofolio</a>
<a href="#">contact</a>
<!--end of Links slidemenu-->
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4">
<div id="text1">
<p>x</p>
</div>
</div>
<div class="col-md-4">
<div id="text2">
<p>x</p>
</div>
</div>
<div class="col-md-4">
<div id="text3">
<p>x</p>
</div>
</div>
</div>
</div>
Optional JavaScript
jQuery first, then Popper.js, then Bootstrap JS
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
A:
I edited a few of your css tags to reposition the navigation
Adding width: 100%; to .nav a fixed the navigation links.
Adding a padding: 10px; to .slide a opens up some space for your menu icon.
Finally adding left: 130px; to .nav .close will move the icon closer to the original position.
@import url('https://fonts.googleapis.com/css?family=Alegreya+Sans:800');
body{
font-family: 'Alegreya Sans', sans-serif;
overflow-x: hidden;
}
.nav{
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
opacity: .9;
overflow-x: hidden;
padding-top: 60px;
transition: .7s;
display: block !important;
}
.nav a {
display: block;
padding: 10px 30px;
font-size: 25px;
text-decoration: none;
color: #ccc;
width: 100%;
}
.nav a:hover {
color: #fff;
transition: .4s;
}
.nav .close{
position: absolute;
top: 0;
right: 22px;
margin-left: 50px;
font-size: 30px;
left: 130px;
}
.slide a{
color: #000;
font-size: 36px;
padding: 10px;
}
#sidemenu{
padding: 20px;
transition: margin-left .7s;
overflow: hidden;
width: 100%;
}
.slide {
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!--scripts-->
<script defer src="https://use.fontawesome.com/releases/v5.0.7/js/all.js">
</script>
<script>
function openSlideMenu() {
document.getElementById('menu').style.width = '250px';
document.getElementById('slidemenu').style.marginLeft= '250px';
}
function closeSlideMenu() {
document.getElementById('menu').style.width = '0px';
document.getElementById('slidemenu').style.marginLeft= '0px';
}
</script>
<!--css-->
<link rel="stylesheet" href="../css/Index.css">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Frontpage</title>
</head>
<body>
<div id="slidemenu">
<span class="slide">
<a href="#" onclick="openSlideMenu()">
<i class="fas fa-bars"></i>
</a>
</span>
<div id="menu" class="nav">
<a href="#" class="close" onclick="closeSlideMenu()">
<i class="fas fa-times"></i>
</a>
<!--Links slidemenu-->
<a href="#">home</a>
<a href="#">about</a>
<a href="#">services</a>
<a href="#">portofolio</a>
<a href="#">contact</a>
<!--end of Links slidemenu-->
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4">
<div id="text1">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
<div class="col-md-4">
<div id="text2">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
<div class="col-md-4">
<div id="text3">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
I changed your nav from display flex to block this means you can customize the padding. The flex display was giving each element an equal height in the view.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Would Your Speed Be Reduced If You Drag A Grappled Opponent Through Difficult Terrain?
Consider this situation: you are facing an opponent who is standing on the border of difficult terrain. You are on a square directly in front of the opponent, but you are not standing on difficult terrain.
You begin your turn with the opponent already grappled. You drag the opponent through difficult terrain, while staying outside of it yourself. Is your movement speed affected because you're dragging someone through difficult terrain?
Scenario
This is a useful combination if you were somehow able to cast Spike Growth with the opponent standing on just the border, and (for flavor) you dragged your opponent's face on the ground after the grapple.
A:
A grappled creature has a movement speed of zero, so it can only be moved by the grappler (or an effect that forces it to move, like thunderwave).
Since the only movement that matters in a grapple is the creature/player doing the actual grappling, that's where the focus lies. The pertinent rules are as follows.
For the grappled target, under the PHB pg.290, title Conditions:
Grappled
• A grappled creature’s speed becomes 0, and it can't
benefit from any bonus to its speed.
And for the rules as they apply to the creature/player doing the grappling; PHB pg.195:
Moving a Grappled Creature.
When you move, you
can drag or carry the grappled creature with you, but
your speed is halved, unless the creature is two or more
sizes smaller than you.
This makes the physical location of the grappled creature entirely irrelevant by RAW since it's movement speed is zero anyways. All that matters is the grappler's location, and the terrain the grappler is moving across.
In addition, your specific scenario would also deal damage to the creature since Spiky Growth does damage. Your movement speed would follow the grappling rules, but the creatures location with respect to the grappler is up to the creature/person that has established the grapple. If you control the target's movement, you can position them wherever you please.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regex - Capture words within boundaries
I am new to Regex and am having difficulty capturing some data from a web scrape. The strings I have are in the form:
\n\n\n\nHELLO & EVERYONE\n What's up?
And I want to capture everything within the 4 \ns and the other \n.
i.e. HELLO & EVERYONE
I haven't been able to get anything to work, something along the lines of / \n{4}(\w+)\n /?
A:
use: (?:\\n){4}(.*)\\n
You will need to wrap your "\n" in a non capturing group otherwise the system will treat it as "try and match n 4 times" instead.
Also \ is a special character so you'll have to specify \\ but note "not applicable to Javascript".
So what that expression means is that, look for \n\n\n\n and then capture everything from there until until you see the next \n
See:
https://regex101.com/r/yA9mV3/1
Also, incase you are doing Javascript, here is an implementation;
var data = "\n\n\n\nHELLO & EVERYONE\n What's up"
var matches = /(?:\n){4}(.*)\n/.exec(data);
console.log(matches[1]);
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.