source
list | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0048663271.txt"
] |
Q:
Identity Server 3 - signin parameter for external login
I am using identity server 3 and I have configured facebook and google as my external login providers.
I have a registration page where I have to show the facebook and google links. When I check the url for that I can see it follows the below format
../identity/external?provider=Google&signin=e41e8ad48d1f282610767112c22a7984
I am stuck with the signin parameter. From where can I generate or get a valid signin parameter so that I can generate a valid link.
A:
I see no point in generating a signin id dynamically, because it will be generated automatically if a there's a valid request for connect/authorize endpoint.
But if you insist on generating signin id yourself, identityserver3 has an extension method for that, which you can use it.
owinContext.Environment.CreateSignInRequest(new SigninMessage(){});
|
[
"stackoverflow",
"0043549211.txt"
] |
Q:
Facebook Marketing API Campaign spend_cap field returns inconsistently
I'm trying to pull data for each of my Ad Campaigns from the Facebook Marketing API.
In the Ads Insights API there is only a 'spend' field that returns how much of the budget for that campaign has been spent so within the specified date range parameter. This is documented at
developers.facebook.com/docs/marketing-api/insights/fields/v2.9
I would like to get the 'spend_cap' field that's specified in the Reference section of the Marketing API located in the link below. One thing I noted was that there are no parameters available to this node, that may be why the spend_cap is not returning. This is documented at
developers.facebook.com/docs/marketing-api/reference/ad-campaign-group
I am using the following url to request the data.
https://graph.facebook.com/v2.9/{act_id}/campaigns?fields=name,spend_cap&access_token={access_token}
However, it returns the spend_cap field inconsistently, as shown below. I've only included a couple examples but I'm certain that all my campaigns are set up with spending caps.
data:[
{
"id": "##############",
"name": "name1",
"start_time": "2016-06-24T14:47:34-0400",
"stop_time": "2016-07-03T14:47:34-0400"
},
{
"id": "##############",
"name": "name2",
"spend_cap": "30000",
"start_time": "2016-05-16T11:57:10-0400"
},
{
"id": "##############",
"name": "name3",
"spend_cap": "15000",
"start_time": "2016-05-16T11:44:06-0400",
"stop_time": "2017-04-01T00:00:00-0400"
},
{
"id": "##############",
"name": "name4",
"start_time": "2016-05-13T15:34:41-0400",
"stop_time": "2017-05-13T09:46:44-0400"
}
]
A:
The spend_cap at the campaign level is an optional field which is why it is only returned for some of the campaigns.
In general within the Graph API, if a field contains no data, this field will be omitted from the response.
Our SDKs abstract this for you so you can always access a field of an object, regardless of whether it was in the response, so if you're not using one of our SDKs, you'll have to do the same.
|
[
"serverfault",
"0000376487.txt"
] |
Q:
Multiple servers for resolving different domains
I was wondering is there a way to configure a linux or windows machine to use separate nameservers depending on what domain is being queried.
Like for internal.example.com it resolves to 192.168.10.7 for example and for the rest go through google at 8.8.8.8.
The Primary reason for this would be use in a VPN.
A:
The usual way to handle this is to configure your own DNS server that forwards requests for non-local domains to other DNS servers.
A:
You can do this in BIND with forwarders on a per-domain basis.
http://www.zytrax.com/books/dns/ch4/index.html#forwarding
http://gleamynode.net/articles/2267/
|
[
"stackoverflow",
"0008398263.txt"
] |
Q:
Need those not in the table
I have a problem... I have three tables: game, gamelist, and player. The game table contains games, the gamelist contains all the players who want to play in a game and the player table contains all the players.
I have made this query:
var query1 = from es in gr.games
join esh in gr.gameLists on es.id equals esh.gameID
where es.holdID == play.holdID && esh.playerID.HasValue && esh.playerID == personID
select es;
This query gets me all the games a player has signed up for... but how do I get all the games he hasn't signed up for? Any hints or ideas?
A:
You could simple invert the join condition, that is select the game items that are not in the gameLists table.
However, since LINQ only supports equi-join, you'll have to express it using a cross join filtered with a where clause:
var results = from es in gr.games
from esh in gr.gameLists
where es.id != esh.gameID &&
esh.playerID.HasValue && esh.playerID == personID
select es;
|
[
"es.stackoverflow",
"0000216781.txt"
] |
Q:
Validar varios inputs
tengo la siguiente duda: por ejemplo en mi formulario de pedido quiero hacer esto: tengo un input en donde ingreso la cantidad de servicios ej 1,2,3,4 etc. en otro el precio y a traves de otro quisiera fijar el impuesto y en otro mostrar el precio con impuesto pero me gustaria saber si se puede hacer de manera automatica, es decir, que al momento de ingresar la cantidad esta se vaya multiplicando por el precio mas el impuesto y se muestre automaticamente en el ultimo input es decir tendria 4 inputs. Saludos, espero me puedan ayudar.
A:
Creo con con algo asi podrias salirte
Servicios: <input type="text" id="services" value="1" onchange="makeCalcs()"/><br>
Precio: <input type="text" id="price" value="0" onchange="makeCalcs()"/><br>
Impuesto: <input type="text" id="iva" value="21" onchange="makeCalcs()"/><br>
Total: <input type="text" id="total" value="0"/><br>
<script>
function makeCalcs() {
var services = document.getElementById("services").value;
var price = document.getElementById("price").value;
var iva = document.getElementById("iva").value;
document.getElementById("total").value = services * price + (iva / 100 * (services * price));
}
</script>
Es bastante simple cada vez que edites uno de los campos el ultimo se actualizara con la información necesaria, ha esto le puedes añadir mas cosas como que no se permitan usar characteres/letras para que solo se usen números. Pero en principio haría su trabajo.
|
[
"stackoverflow",
"0041778968.txt"
] |
Q:
How to enable a JAVADOC view in Android Studio
When commenting a method in Eclipse, we have the possibility to select the method with the mouse and the Javadoc comment is popping up on the screen, which is very helpful to me.
That's what I am missing in Android Studio.
Can we do the same in Android Studio?
A:
select the source item
menu > View > Quick Documentation
then Documentation view should appear on right-hand side.
A:
if you type /** before the method declaration and press Enter, the javadoc comment block will be generated automatically.
/**
*
* @param
* @param
*/
|
[
"stackoverflow",
"0000047612.txt"
] |
Q:
How to do C++ style destructors in C#?
I've got a C# class with a Dispose function via IDisposable. It's intended to be used inside a using block so the expensive resource it handles can be released right away.
The problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally.
In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using.
Is there any way to for a using block to be automatically used in C#?
Many thanks.
UPDATE:
I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.
Here's the bug I found, reduced to the essentials...
try
{
PleaseDisposeMe a = new PleaseDisposeMe();
throw new Exception();
a.Dispose();
}
catch (Exception ex)
{
Log(ex);
}
// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();
Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?
A:
Where I work we use the following guidelines:
Each IDisposable class must have a finalizer
Whenever using an IDisposable object, it must be used inside a "using" block. The only exception is if the object is a member of another class, in which case the containing class must be IDisposable and must call the member's 'Dispose' method in its own implementation of 'Dispose'. This means 'Dispose' should never be called by the developer except for inside another 'Dispose' method, eliminating the bug described in the question.
The code in each Finalizer must begin with a warning/error log notifying us that the finalizer has been called. This way you have an extremely good chance of spotting such bugs as described above before releasing the code, plus it might be a hint for bugs occuring in your system.
To make our lives easier, we also have a SafeDispose method in our infrastructure, which calls the the Dispose method of its argument within a try-catch block (with error logging), just in case (although Dispose methods are not supposed to throw exceptions).
See also: Chris Lyon's suggestions regarding IDisposable
Edit:
@Quarrelsome: One thing you ought to do is call GC.SuppressFinalize inside 'Dispose', so that if the object was disposed, it wouldn't be "re-disposed".
It is also usually advisable to hold a flag indicating whether the object has already been disposed or not. The follwoing pattern is usually pretty good:
class MyDisposable: IDisposable {
public void Dispose() {
lock(this) {
if (disposed) {
return;
}
disposed = true;
}
GC.SuppressFinalize(this);
// Do actual disposing here ...
}
private bool disposed = false;
}
Of course, locking is not always necessary, but if you're not sure if your class would be used in a multi-threaded environment or not, it is advisable to keep it.
A:
Unfortunately there isn't any way to do this directly in the code. If this is an issue in house, there are various code analysis solutions that could catch these sort of problems. Have you looked into FxCop? I think that this will catch these situations and in all cases where IDisposable objects might be left hanging. If it is a component that people are using outside of your organization and you can't require FxCop, then documentation is really your only recourse :).
Edit: In the case of finalizers, this doesn't really guarantee when the finalization will happen. So this may be a solution for you but it depends on the situation.
|
[
"stackoverflow",
"0019048247.txt"
] |
Q:
in robotium how to handle multiple classes
i am having the same problem
i am using 3 classes(classA, ClassB , ClassC ), and solo_d class, in my ClassC i am having test and in ClassA and ClassB i am using solo.sleep only
public class ClassA extends Solo_d{
public void click_on_save(){
Log.v("Test" , "Test in classA");
solo.sleep(5000); // getting error null pointer exception
solo.clickOnText("Saved")
}}
public class ClassC extends Solo_d {
ClassA aa = new ClassA();
@Test
public void test001(){
Log.v("Test" , "Test Start ");
aa.click_on_save();
}}
and i am using ClassB same as classA and using in ClassC
in Solo_d class i have given proper Activity and solo definition its working fine individual and also working fine if i am using as ClassB extends Solo_d
ClassA extends ClassB
ClassC extends ClassA
but if i do not want to extend ClassA in ClassB , ClassB in ClassC
it will be difficult to know the sequence of the inheritance
but i am getting NullPointerException
anybody can help on this
A:
I suppose you need to add constructor to class A and remove "extends Solo_d"
public class ClassA{
static Solo solo;
//contructor
public ClassA(Solo _solo){
solo = _solo
}
public void click_on_save(){
Log.v("Test" , "Test in classA");
solo.sleep(5000);
solo.clickOnText("Saved");
}
}
and in your ClassC:
public class ClassC extends Solo_d {
@Test
public void test001(){
ClassA aa = new ClassA(solo);
Log.v("Test" , "Test Start ");
aa.click_on_save();
}
}
You could create the same constructor in you ClassC and call it in your Solo_d class (for example, in your setUp() method)
public class ClassC {
static Solo solo;
public ClassC(Solo _solo){
solo = _solo
}
ClassA aa = new ClassA(solo);
@Test
public void test001(){
Log.v("Test" , "Test Start ");
aa.click_on_save();
}
}
It works for me, hope it will be helpful for you.
|
[
"dba.stackexchange",
"0000060753.txt"
] |
Q:
Help with SQLPSX output for replication
I am using the CodePlex project SQL Server PowerShell Extensions (SQLPSX) to generate script files for replication. Everything is working as I want except for one thing. I have looked through the PowerShell code to see if I could suppress this and could not find it. I have tried to create secondary process to remove this item, but my PowerShell skills are not that great.
The output has this line that I do not want.
exec [DatabaseName].sys.sp_addqreader_agent @job_login = null, @job_password = null, @frompublisher = 1
GO
We do not use qreader and I don't want this in my output files.
My question is two fold.
1.) Does anyone know how I can modify the SQLPSX code to not write this output. (Preferred)
2.) Add to PowerShell script below to loop through all output files created and remove the two lines listed above.
PowerShell script I found that loops through and generates output files.
param ($sqlServer,$path,[switch]$scriptPerPublication)
Import-Module Repl
if ($sqlServer -eq "")
{
$sqlserver = Read-Host -Prompt "Please provide a value for -sqlServer"
}
if ($path -eq "")
{
$path = Read-Host -Prompt "Please provide a value for output directory path"
}
$scriptOptions = New-ReplScriptOptions
$scriptOptions.IncludeArticles = $true
$scriptOptions.IncludePublisherSideSubscriptions = $true
$scriptOptions.IncludeCreateSnapshotAgent = $true
$scriptOptions.IncludeGo = $true
$scriptOptions.EnableReplicationDB = $true
$scriptOptions.IncludePublicationAccesses = $true
$scriptOptions.IncludeCreateLogreaderAgent = $true
$scriptOptions.IncludeCreateQueuereaderAgent = $true
$scriptOptions.IncludeSubscriberSideSubscriptions = $true
$distributor = Get-ReplServer $sqlserver
if($distributor.DistributionServer -eq $distributor.SqlServerName)
{
$distributor.DistributionPublishers | ForEach-Object {
$distributionPublisher = $_
if($distributionPublisher.PublisherType -eq "MSSQLSERVER")
{
$outPath = "{0}\from_{1}\{2}\" -f $path,$distributionPublisher.Name.Replace("\","_"),$((Get-Date).toString('yyyy-MMM-dd_HHmmss'))
New-Item $outPath -ItemType Directory | Out-Null
Get-ReplPublication $distributionPublisher.Name | ForEach-Object {
$publication = $_
$fileName = "{0}{1}.sql" -f $outPath,$publication.DatabaseName.Replace(" ", "")
if($scriptPerPublication)
{
$fileName = "{0}{1}_{2}.sql" -f $outPath,$publication.DatabaseName.Replace(" ", ""),$publication.Name.Replace(" ", "")
}
Write-Debug $("Scripting {0} to {1}" -f $publication.Name.Replace(" ", ""),$fileName)
Get-ReplScript -rmo $publication -scriptOpts $($scriptOptions.ScriptOptions) | Out-File $fileName
}
}
}
}
else
{
$outPath = "{0}\from_{1}\{2}\" -f $path,$distributor.SqlServerName.Replace("\","_"),$((Get-Date).toString('yyyy-MMM-dd_HHmmss'))
New-Item $outpath -ItemType Directory | Out-Null
Get-ReplPublication $distributor.SqlServerName | ForEach-Object {
$publication = $_
$fileName = "{0}{1}.sql" -f $outPath,$publication.DatabaseName.Replace(" ", "")
if($scriptPerPublication)
{
$fileName = "{0}{1}_{2}.sql" -f $outPath,$publication.DatabaseName.Replace(" ", ""),$publication.Name.Replace(" ", "")
}
Write-Debug $("Scripting {0} to {1}" -f $publication.Name.Replace(" ", ""),$fileName)
Get-ReplScript -rmo $publication -scriptOpts $($scriptOptions.ScriptOptions) | Out-File $fileName
}
}
A:
In the $scriptingoptions collection, you are explicitly setting on the Queue reader agent export. Change this line:
$scriptOptions.IncludeCreateQueuereaderAgent = $true
to
$scriptOptions.IncludeCreateQueuereaderAgent = $false
If you want help with the module you are using, you need to show the code you are using to generate the scripts.
|
[
"superuser",
"0000040961.txt"
] |
Q:
Restrict iTunes smart playlist to audio only
I have a smart playlist of my favorite podcasts which I use for commuting -- it's mostly a simple collection of "Album contains This Week in Tech" or "Album contains Croncast", etc.
The feed from The Radio Adventures of Dr. Floyd sometimes includes video episodes. I want to edit my smart playlist so that the video episodes aren't included so that I don't get tempted to look over at my iPhone while driving.
I've tried removing "Media Kind is Music Video" and "Media Kind is Movie" but these appear to have media kind as "podcast" -- just like the audio only episodes.
Anybody know a way to tell the iTunes 9 smart playlists to include only audio files?
A:
Remove where Kind is video and video kind is movie. That will take care of your problems.
|
[
"stackoverflow",
"0038781356.txt"
] |
Q:
limiting maximum number of rolled up log files in log4j2
I am using log4j2 to provision logging in my code.
I am using the time based trigger policy.
However the delete is not working for me and I am getting the following error
016-08-05 14:44:22,635 main ERROR appender RollingFile has no parameter that matches element Delete
2016-08-05 14:44:22.686 [WARN ] [main] Class1 - new cycle
2016-08-05 14:44:22.691 [DEBUG] [main] Class1 - Hello this is a debug message
2016-08-05 14:44:22.691 [INFO ] [main] Class1 - Hello this is an info message
2016-08-05 14:44:22.692 [FATAL] [main] Class1 - Beaware This is a Fatal message
2016-08-05 14:44:22.692 [ERROR] [main] Class1 - This is an error message
2016-08-05 14:44:22.692 [INFO ] [main] Class2 - In constructor of class2
2016-08-05 14:44:22.692 [INFO ] [main] Class1 - Repeating cycle
2016-08-05 14:44:22.692 [DEBUG] [main] Class1 - Hello this is a debug message
2016-08-05 14:44:22.692 [INFO ] [main] Class1 - Hello this is an info message
2016-08-05 14:44:22.693 [FATAL] [main] Class1 - Beaware This is a Fatal message
2016-08-05 14:44:22.693 [ERROR] [main] Class1 - This is an error message
Below is my log4j2 config file
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Properties>
<Property name="log-path">D:/logs</Property>
</Properties>
<Appenders>
<Console name="console-log" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%t] %c{1} - %msg%n" />
</Console>
<RollingFile name="file-log" fileName="${log-path}/custom-log.log"
filePattern="${log-path}/customelog-%d{yyyy-MM-dd HH-mm}.log">
<PatternLayout>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%t] %c{1} - %msg%n
</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
<Delete basePath="${log-path}" maxDepth="2">
<IfFileName glob="customelog-*.log" />
<IfLastModified age="1m" />
</Delete>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="test.Class1" level="debug" additivity="false">
<appender-ref ref="file-log" level="debug" />
<appender-ref ref="console-log" level="debug" />
</Logger>
<Root level="all" additivity="false">
<AppenderRef ref="console-log" />
</Root>
</Loggers>
</Configuration>
My test code is below
class1.java:
package test;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Class1 {
public static Logger logger = LogManager.getLogger(Class1.class);
public static void main(String[] args){
logger.warn("new cycle");
logger.debug("Hello this is a debug message");
logger.info("Hello this is an info message");
logger.fatal("Beaware This is a Fatal message");
logger.error("This is an error message");
Class2 obj = new Class2();
logger.info("Repeating cycle");
logger.debug("Hello this is a debug message");
logger.info("Hello this is an info message");
logger.fatal("Beaware This is a Fatal message");
logger.error("This is an error message");
}
}
Class2.java
package test;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Class2 {
public static Logger logger = LogManager.getLogger(Class2.class);
public Class2(){
Class2.logger.info("In constructor of class2");
}
}
The problem is the error stated above and the fact that the files are not getting deleted if there age is more than 1 minute
Can you please let me know what mistake I am making because of which my delete functionality is not working?
I have used the following example here Log4j2 - Configure RolloverStrategy to delete old log files
Thanks,
Vikas
A:
It looks like your Delete tag should be wrapped in a DefaultRolloverStrategy
e.g.
<RollingFile name="RollingFile" fileName="D:/app.log"
filePattern="D:/app-%d{yyyy-MM-dd-HH-mm-ss}.log">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="60" modulate="true"/>
<!--<SizeBasedTriggeringPolicy size="250 MB"/>-->
</Policies>
<DefaultRolloverStrategy>
<Delete basePath="D:" maxDepth="1">
<IfFileName glob="app-*.log" />
<IfLastModified age="3m" />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
|
[
"gis.stackexchange",
"0000181669.txt"
] |
Q:
Is it possible to have Feature Dataset in another Feature Dataset?
Understand from ArcGIS website that we can use feature dataset to group together related feature classes.
Is it possible to have another feature dataset in another feature dataset? Understand that there is a performance issue if we have too many things under one feature dataset, but at this point, it is very unlikely to have a lot of accessing the dataset once it is added.
The scenario that I tried to achieve:
1. Have a Report and archive feature dataset to group reports and archives.
2. In each of this feature dataset, it will be further grouped by different category.
For example:
Report Dataset
Report Type A Dataset
Report October 2014 Feature Class
Report November 2014 Feature Class
Archive Dataset
Report Type A Dataset
Report October 2013 Feature Class
Report November 2013 Feature Class
If it is not possible, any other suggestion to achieve this? For example: Create a folder instead of Feature dataset. (Heard that there is a way to do this using ArcGIS command line tools?)
A:
Although some people use feature datasets as "geodatabase folders" they are not intended for that purpose and quite poor at it. For example, feature datasets cannot contain tables, cannot contain feature classes with different coordinate systems, and only one level of "geodatabase sub-folder" is possible.
The GIS Dictionary definition of a geodatabase feature dataset is:
In a geodatabase, a collection of feature classes stored together so
they can participate in topological relationships with one another.
All the feature classes in a feature dataset must share the same
spatial reference; that is, they must have the same coordinate system
and their features must fall within a common geographic area. Feature
classes with different geometry types may be stored in a feature
dataset. In ArcGIS, feature classes that participate in a geometric
network must be placed in a feature dataset.
A workaround to achieve what you are trying to do, which is to get a "super folder" for your feature datasets, is by using multiple geodatabases.
Report Geodatabase
Report Type A Feature Dataset
Report October 2014 Feature Class
Report November 2014 Feature Class
Archive Geodatabase
Report Type A Feature Dataset
Report October 2013 Feature Class
Report November 2013 Feature Class
|
[
"unix.stackexchange",
"0000278215.txt"
] |
Q:
Add TCP congestion control variant to Linux Ubuntu
I want to test different variants of TCP in Linux Ubuntu. I have Ubuntu 14.04 LTS with Kernel version 3.14. When I check the available congestion control algorithm using the following command sysctl net.ipv4.tcp_available_congestion_control I get only: cubic and reno. However, I want to test other variants like Hybla, HighSpeed. If I run the menuconfig I can select the variants which I want and compile the Kernel. But in my case, I already have the kernel compiled so is it possible to have some Linux package which contains TCP variants as loadable kernel modules?
A:
Have a look here to see what modules you have installed...
ls -la /lib/modules/$(uname -r)/kernel/net/ipv4
You should get a list of modules, I got this.
tcp_bic.ko
tcp_diag.ko
tcp_highspeed.ko
tcp_htcp.ko
tcp_hybla.ko
tcp_illinois.ko
tcp_lp.ko
tcp_scalable.ko
tcp_vegas.ko
tcp_veno.ko
tcp_westwood.ko
You can see what your kernel has configured by greping your config file for TCP_CONG ie
grep TCP_CONG /boot/config-$(uname -r)
CONFIG_TCP_CONG_ADVANCED=y
CONFIG_TCP_CONG_BIC=m
CONFIG_TCP_CONG_CUBIC=y
CONFIG_TCP_CONG_WESTWOOD=m
CONFIG_TCP_CONG_HTCP=m
CONFIG_TCP_CONG_HSTCP=m
CONFIG_TCP_CONG_HYBLA=m
CONFIG_TCP_CONG_VEGAS=m
CONFIG_TCP_CONG_SCALABLE=m
CONFIG_TCP_CONG_LP=m
CONFIG_TCP_CONG_VENO=m
CONFIG_TCP_CONG_YEAH=m
CONFIG_TCP_CONG_ILLINOIS=m
CONFIG_DEFAULT_TCP_CONG="cubic"
To try one of these you need to install it using modprobe -a tcp_westwood or whatever you want. You can then test it using this
echo "westwood" > /proc/sys/net/ipv4/tcp_congestion_control
|
[
"stackoverflow",
"0034321051.txt"
] |
Q:
Regarding operation flow in a bash script
I was just wondering, in a bash script, if I have a command on one line to say rsync a large file (~10GB) then the next command on the next line is meant to rename then move that same file, will the script know to wait for the rsync to complete before attempting the rename and move?
Is there a flag or something I can put on each line to make it wait before executing the next command?
Sorry if this seems like a total noob question, but alas I am a noob!
Thanks in advance for any info!
A:
All commands are executed in sequence, so, a command will wait for the previous command to complete. Only when you add a & to the end of a command will it run in the background, and thus not wait for completion before executing the next.
|
[
"stackoverflow",
"0019197014.txt"
] |
Q:
What is precisionStep in very simple terms?
I tried understanding precisionStep at several places but cannot fully understand its concept. So, please explain what it is about, in very simple words.
A:
The precisionStep is a count, after how many bits of the indexed value a new term starts. The original value is always indexed in full precision. Precision step of 4 for a 32 bit value(integer) means terms with these bit counts:
All 32, left 28, left 24, left 20, left 16, left 12, left 8, left 4 bits of the value (total 8 terms/value). A precision step of 26 would index 2 terms: all 32 bits and one single term with the remaining 6 bits from the left.
|
[
"tex.stackexchange",
"0000326519.txt"
] |
Q:
Vertical alignment between a custom symbol and text
I managed to include symbols inside custom fonts (.ttf):
\documentclass[12pt]{article}
\usepackage{fontspec}
\newcommand*{\icmobile}{{\fontspec{mat.ttf}\symbol{"E0D4}}}
\newcommand*{\icpin}{{\fontspec{mat.ttf}\symbol{"E55E}}}
\newcommand*{\icmail}{{\fontspec{mat.ttf}\symbol{"E158}}}
\newcommand*{\icarrowr}{{\fontspec{mat.ttf}\symbol{"E5CC}}}
\begin{document}
\icmail \hspace{2mm} [email protected]
\begin{itemize}
\item[\icarrowr] one
\item[\icarrowr] two
\item three \dots{}
\end{itemize}
\end{document}
But I can not vertically align text and symbols.
...as you can see the symbol is always higher than the text.
I'm creating the custom fonts symbols correctly? It's possible to achieve the vertical center alignment between symbol and text?
Thanks in advance.
A:
If a 'glyph' or box is too high or low compared to the baseline, it is possible to raise or lower it with \raisebox{dimension value}{content}. Positive values raise the content, negative values shift it down.
The precise value depends on the font size declarations and the details of the symbol actually.
Perhaps it is possible to query the depth of the glyph box.
|
[
"stackoverflow",
"0005995591.txt"
] |
Q:
multi dimensional object
how can you make a multi dimensional object??
function tst(){
this.a = function(){
alert(this.b.abc.c());
};
this.b = function(){
};
}
var obj = new tst();
obj.b.abc = function(){
this.c = function(){
return 'hello world';
};
};
obj.a();
A:
The problem is with this code:
obj.b.abc = function(){
this.c = function(){
return 'hello world';
};
};
Calling the abc function will not create a obj.b.abc.c function, but a obj.b.c function. Therefore, this.b.abc.c() throws an error because such a function doesn't exist.
This will make it work:
function tst() {
this.a = function() {
alert( this.b.abc.c() );
};
this.b = function() {
};
}
var obj = new tst();
obj.b.abc = function() {
this.abc.c = function() { // <--- NEW
return 'hello world';
};
};
obj.b.abc(); // <--- NEW
obj.a();
Live demo: http://jsfiddle.net/vgpNU/
|
[
"stackoverflow",
"0017084380.txt"
] |
Q:
CC3MeshNode is not affected by light in cocos3d
I have drawn a complex 3d shape using CC3MeshNode in cocos3d, but this shape is not affected (shadow and bright places depending on positioning) by the light source (lamp) that i set in the world, where if i use one of the populateAs methods to draw something like a sphere it will get affected by the light source.
What should i do while manually drawing a CC3MeshNode so that it will get affected by light.
Here is a sample code of drawing a rectangle manually in cocos3d
CC3MeshNode *pMeshNode = [[CC3MeshNode alloc] init];
[pMeshNode setIsTouchEnabled:YES];
CC3Mesh* theArrayMesh = [pMeshNode prepareParametricMesh];
// Prepare the vertex content and allocate space for vertices and indices.
[theArrayMesh ensureVertexContent];
theArrayMesh.allocatedVertexCapacity = totalVertexCount;
theArrayMesh.allocatedVertexIndexCapacity = (triangleCount * 3);
GLushort* indices = theArrayMesh.vertexIndices.vertices;
/*
* 1-------0
* | /| -z
* | / | ⥣
* | / | =>+x
* | / |
* | / |
* | / |
* |/ |
* 2-------3
*/
{
[theArrayMesh setVertexLocation: cc3v(3, -3,0) at: 3];
[theArrayMesh setVertexLocation: cc3v(-3, -3,0 ) at: 2];
[theArrayMesh setVertexLocation: cc3v(-3, 3, 0) at: 1];
[theArrayMesh setVertexLocation: cc3v(3, 3, 0) at: 0];
}
GLubyte indxIndx = 0;
GLubyte vtxIndx = 0;
for (int side = 0; side < 1; side++) {
// First trangle of side - CCW from bottom left
indices[indxIndx++] = vtxIndx++; // vertex 0
indices[indxIndx++] = vtxIndx++; // vertex 1
indices[indxIndx++] = vtxIndx; // vertex 2
// Second triangle of side - CCW from bottom left
indices[indxIndx++] = vtxIndx++; // vertex 2
indices[indxIndx++] = vtxIndx++; // vertex 3
indices[indxIndx++] = (vtxIndx - 4); // vertex 0
}
[self addChild:pMeshNode];
A:
I think the problem is you need to supply vertex normals for your mesh. Normals are required for the lighting calculations to operate correctly. The routines to automatically populate a sphere, etc. are generating and storing vertex normals in the mesh. Desktop OpenGL will generate normals for a mesh without them when you use glEnable(GL_AUTO_NORMAL), but this functionality doesn't exist in mobile, at least not in OpenGL ES 2.0.
|
[
"stackoverflow",
"0049777593.txt"
] |
Q:
How to file copy from a column of files in a data table in R
I am trying to create a new folder with all the files I need. I have a datatable called newlist with a column called fullpath which has the file path for each file.
I have tried the code below but the error message says "'from' path too long" so I don't think it recognises the values as separate file paths.
file.copy(from=newlist[,"fullpath"], to=destination, overwrite=TRUE, recursive=TRUE)
I think I need to specify the files to copy first using the list.files() function but I am unsure how to do this with a column of files in a datatable.
A:
Try this:
lapply(newlist[,"fullpath"], function(x) file.copy(from=x, to=destination, overwrite=TRUE, recursive=TRUE))
Edit:
If your paths do not contain extensions, you can use this code instead:
lapply(newlist[,"fullpath"], function(x) {
# Find the file in the given directory with the basename and add a wildcard extension
f <- file.path(dirname(x), list.files(dirname(x), paste0(basename(x), ".*")))
file.copy(from=f, to=destination, overwrite=TRUE, recursive=TRUE)
})
|
[
"gis.stackexchange",
"0000059146.txt"
] |
Q:
Where to find books or course materials to help prepare for Esri Technical Certification in ArcGIS Desktop and Developer?
Where I can find books or course materials to help prepare for Esri Technical Certification in ArcGIS Desktop and Developer?
A:
If you check the ESRI Technical Certification website, under each level (e.g. Desktop 10.1) they provide a PDF with a thorough list of resources including training courses, web lessons and books from ESRI Press.
|
[
"stackoverflow",
"0037324873.txt"
] |
Q:
How to make a URL which has parameter values wrapped around a JSON Object for invoking an API?
I made a registration system which returns certain values and updates a database everytime a HTML form is submitted. Here is the code for register.php
<?php
require_once "include/functions.php";
$db = new functions;
//json response array
$response = array("error" => FALSE);
if($_SERVER['REQUEST_METHOD'] === 'POST'){
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['confirm_password']) && !empty($_POST['name']) && !empty($_POST['email'])
&& !empty($_POST['password']) && !empty($_POST['confirm_password'])){
//receiving the POST parameters
$name = $db->sanitizeString($_POST['name']); //Sanitizing the string
$email = $db->sanitizeString($_POST['email']);
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
//check if password is equal to confirm_password to continue
if($db->passwordsMatch($password, $confirm_password)){
//check whether user exists with the same validated email
if($db->userExist($email) && filter_var($email, FILTER_VALIDATE_EMAIL)){
//user exists already
$response["error"]= TRUE;
$response["error_msg"]= "User already exists with email". $email;
echo json_encode($response);
}
else if(!($db->userExist($email)) && filter_var($email, FILTER_VALIDATE_EMAIL)){
//user does not exist
$hash= bin2hex(openssl_random_pseudo_bytes(78));
$user= $db-> storeUser($name, $email, $password, $hash);
if($user){
//new user
$response["error"]= FALSE;
$response["uid"]= $user["unique_id"];
$response["user"]["name"]= $user["name"];
$response["user"]["email"]= $user["email"];
$response["user"]["created_at"]= $user["created_at"];
$response["user"]["updated_at"]= $user["updated_at"];
$response["user"]["status"]= $user["status"];
echo json_encode($response);
$db->sendEmail($email, $hash);
}
else{
//user failed to store
$response["error"]= TRUE;
$response["error_msg"]= "Unknown error occurred in registration";
echo json_encode($response);
}
}
else{
//email address is not valid
$response["error"]= TRUE;
$response["error_msg"]= "Invalid email address ".$email;
echo json_encode($response);
}
}
//password and confirm password do not match
else{
$response["error"]= TRUE;
$response["error_msg"]= "Password and Confirm password mismatch";
echo json_encode($response);
}
}
//Some parameters may be missing in the form being submitted
else{
$response["error"]= TRUE;
$response["error_msg"]= "Required parameters are missing";
echo json_encode($response);
}
}
?>
functions.php basically has all the helper functions needed for register.php.
Now I want to use this file which can be called from an Android device for registration. Now the person making the Android part asks me to provide a readymade url needed to invoke the API and he send me an example of an URL which has param values wrapped in a JSON Object.
Can someone please help me to understand what he is actually asking of me and what do I really need to provide.
EDIT
The example URL provided to me by the Android person is this
http://umbria4.prosperoware.com/Api/Account/PingrequestObject={"authentication":{"AppId":"c30605e1-4920-48ff-88d0-e5b95d9f9f27","password":"umbria","username":"alexey.marcus","useWindowsAuthentication":"false"}}
A:
Based on your question => your php part should listen for 2 types of requests, Kind of:
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// your code here
} elseif( $_SERVER['REQUEST_METHOD'] === 'GET' ){
try{
$authentication = json_decode($_GET['PingrequestObject']);
if(isset($authentication->name) && isset($authentication->email) && isset($authentication->password) && // etc...) ){
// make your code here
}
}catch(Exception $ex){
echo $ex->getMessage();
}
}
|
[
"stackoverflow",
"0026595374.txt"
] |
Q:
.htaccess does not redirects to custom 404 page
I'm currently working on my own website which runs on an local Apache Server.
I have a .htaccess file which is supposed to redirect 404 errors to a custom page.
Here it is:
ErrorDocument 404 /404.php
But all I get is the following error instead of my custom 404 page:
Not Found
The requested URL /my-site/gqehgr was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to
use an ErrorDocument to handle the request.
Apache/2.4.9 (Win32) PHP/5.5.12 Server at localhost Port 80
I saw on several forums that I could use the RewriteEngine but I don't understand how it works.
Does anybody have a clue?
EDIT:
The line should be:
ErrorDocument 404 /my-site/404.php
A:
Your 404.php can not be found. Check your files. Try to request /404.php manually.
|
[
"stackoverflow",
"0025142794.txt"
] |
Q:
nginx enforce https works for www.example.com but not for example.com
i've implemented https enforcing through nginx in ubuntu server 12.04 lts. nginx version: nginx/1.1.19. I've added a conf file in the path /etc/nginx/conf.d/https.conf and include it from nginx.conf. it looks like:
server {
listen *:80;
server_name example.com www.example.com;
return 301 https://www.example.com$request_uri;
}
the rest of the config is just default:
user www-data;
worker_processes 4;
pid /var/run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
##
# nginx-naxsi config
##
# Uncomment it if you installed nginx-naxsi
##
#include /etc/nginx/naxsi_core.rules;
##
# nginx-passenger config
##
# Uncomment it if you installed nginx-passenger
##
#passenger_root /usr;
#passenger_ruby /usr/bin/ruby;
##
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
when accessing through www.example.com it correctly redirects me to the https version of the web.
Instead, when accessing through example.com it just goes through http version when should be redirected to https://www.example.com.
Is there something wrong in the configuration? Application servers is listening in 9000 and 9443 ports (http and https respectively) and are being forwarded by iptables through these rules:
-A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 9000
-A PREROUTING -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 9443
Thanks in advance
A:
The problem was that nginx was being bypassed by iptables with the rule:
-A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 9000
which I used previous to nginx installation. Actually nginx is a server listening in some port while iptables works at kernel level.
When removing this rule then all traffic on :80 went through nginx no matter if it was www.mysite.com , mysite.com with or without http prefix or any combination as I intended to.
|
[
"stackoverflow",
"0037643171.txt"
] |
Q:
How do you get a Word add-in to show in Mac Word 2016?
I am trying to follow the basic proof-of-concept office.js / add-in for Mac Word 2016.
I can see the ability to add add-ins, but none of my manifests show.
Reference: Office.js for Word 2016 Mac.
The instructions call for putting the xml in a folder named "wef"...here's the path to MY wef:
/Users/11trees/Library/Containers/com.microsoft.Word/Data/Documents/wef
All the instructions suggest the following path (so no specific username):
Users/Library/Containers/com.microsoft.word/Data/Documents/wef
Maybe I'm missing something totally obvious...or perhaps the difference in location isn't the reason my manifests aren't showing.
The manifests I'm using are the Boilerplate and SillyStories examples from the web - verbatim.
Thank you for any help.
Updating with Manifest:
<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:type="TaskPaneApp">
<Id>0e978793-8a1a-43c9-b8bb-762db69bdfae</Id>
<Version>1.0.0.0</Version>
<ProviderName>11trees</ProviderName>
<DefaultLocale>en-US</DefaultLocale>
<DisplayName DefaultValue="Boilerplate content" />
<Description DefaultValue="Insert boilerplate content into a Word document." />
<Hosts>
<Host Name="Document"/>
</Hosts>
<DefaultSettings>
<SourceLocation DefaultValue="http://127.0.0.1:8080" />
</DefaultSettings>
<Permissions>ReadWriteDocument</Permissions>
</OfficeApp>
A:
/Users/11trees/Library/Containers/com.microsoft.Word/Data/Documents/wef is the correct path for 11trees.
When you select the Insert tab > My Add-ins, are you selecting the button or the drop down portion of the button? The add-in should be listed in the drop down. If not, there is a chance that there is an error with the manifest. Can you post your manifest here?
Update 6/6: it looks like the comment is causing the manifest to not be registered by Word. When I removed the comment in the SillyStories manifest, I could see the add-in in the drop down.
The boilerplate content manifest is working fine for me with version 15.22 (160501)
|
[
"serverfault",
"0000472637.txt"
] |
Q:
Is this a real or virtual server?
Provided the following screenshot and the suspicius Red Hat VirtIO NIC, is this server a dedicated one or a VPS (VM)?
Click to view in original size.
Thanks in advance!
A:
Red hat virtio ethernet, qemu dvd, red hat virtio scsi. This is a VPS running KVM on the real server.
|
[
"stackoverflow",
"0056446428.txt"
] |
Q:
how to get config data from appsettings.json with asp.net core & react
I'm using asp.net core with react/redux and i'm trying to move my config data that is in react/redux into the appsettings.json file. But once the config data has been moved; how is the config data accessible to the ClientApp?
I'm using the Reactjs with Redux starter for ASP.NET Core.
update
If this is not the recommended way to store app configs please let me know what is.
A:
I would not recommend reading the config file from your client side. But if you want to do I would suggest you create a service that read the json file and expo some configuration for client side.
You can config from ASP.Net Core side like this
Example you have config like this in your json
"EmailSettings": {
"MailServer": "",
"MailPort": ,
"Email": "",
"Password": "",
"SenderName": "",
"Sender": "",
"SysAdminEmail": ""
},
So you need to define the matching model with config
public class EmailSettings
{
public string MailServer { get; set; }
public int MailPort { get; set; }
public string SenderName { get; set; }
public string Sender { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string SysAdminEmail { get; set; }
}
Then register in Startup.cs
services.Configure<EmailSettings>(configuration.GetSection("EmailSettings"));
So you can use in your service
private readonly IOptions<EmailSettings> _emailSetting;
public EmailSender(IOptions<EmailSettings> emailSetting)
{
_emailSetting = emailSetting;
}
public string GetConfig(){
return _emailSetting.Value.SenderName;
}
|
[
"stackoverflow",
"0052052231.txt"
] |
Q:
How to write Chinese quotes in Bookdown
I had tested in bookdown template, and found that “”, which is Chinese quotes, would be translated to ``,''。 But if you write “” in a block or other begin,end blocks, the Chinese quotes, “”, would not be translated to ``,''。So you will get different Chinese quotes, in the final pdf file. Can I set in some place to turn off such translation? Thank you.
A:
I use another method.
% 解决双引号不一致的问题。
\newcommand\cqh{“} % chinese quote head
\newcommand\cqt{”} % chinese quote tail
or add space after ``''. The solution is not very good. I add md_extensions: -smart make no sense.
For English, `` '' works very well, but In Chinese, it becomes ugly. Hope pandoc become good enough.
|
[
"stackoverflow",
"0030630384.txt"
] |
Q:
background image of div element can't show in php file
I had a .html file which uses css to assign div's background-image.
The thing is when it's .html it works, I want to change it to .php and I can't figure out how to make the image show.
I saw this question and the answer didn't help me, using url('<?php echo $img;?'> and <?php $img="bg.gif";?> didn't work.
this is sample code :
<?php
$bg = "bg.gif";
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar-sy"> <head>
<meta charset="utf-8">
<style>
html,body {margin: 0px; padding:0px;background-image:url('<?php echo $bg;?>'); }
</style>
</head>
<body>
<div id="wrapper">
<div id="content">
<div id="header">
<div id="logo">
</div>
<div id="links">
</div>
</div>
<div id="mainimg">
</div>
</div>
</div>
</body>
</html>
the body doesn't get filled with the image, although I have the image right with the php file in the same folder.
So what to do ?
Edit
I tried absolute path and still the image doesn't show, also I'm running linux mint 17.1 64 bit, "bg.gif" has all the permissions it needs(group can read and write, other can read and write too).
Inspecting with my browser(opera), it says "failed to load resource , server responded with 404 not found".
A:
Problem solved, When inspecting from my browser I forgot to see where it looks.
I was using codeignitor , the website is acessed from index.php so when you say $bg="bg.gif" it will look for the image under pathtoyourproject/index.php/bg.gif, I solved it by moving the image besides bg.gif and put $bg="../bg.gif" so it doesn't look under index.php.
As for the absolute path, if the absolute path was /var/www/... then it was looking under http://localhost/var/www/... which is equivalent to looking under /var/www/html/var/www/... , that's why it didn't work.
|
[
"stackoverflow",
"0002237877.txt"
] |
Q:
convert code+comment in source control into a readable documentation
We are using mercurial-hg and git, and are wondering if there is a way to create documentations from the existing code and newly check-ed in code.
Is there any plugin that we can hook into mercurial-hg/git that generates documentations?
Thanks
A:
Hooks plus doxygen should do the trick.
|
[
"stackoverflow",
"0038549616.txt"
] |
Q:
Travis determine which files changed
I have a Travis script that runs for every push.
I need to determine which files were modified in this push.
Currently, I have this:
CHANGED_FILES=($(git diff --name-only HEAD HEAD~1))
The problem is that sometimes a push can include more than one commits, and this only looks at the last commit.
What is the expected way to solve this?
A:
I found out there is a Travis environment variable: $TRAVIS_COMMIT_RANGE.
Then it was only a matter of changing the script to:
CHANGED_FILES=($(git diff --name-only $TRAVIS_COMMIT_RANGE))
|
[
"stackoverflow",
"0040719471.txt"
] |
Q:
Filter object by array of property names
I have an object like so
var obj = { name1: somevalue1, name2: somevalue2, name3: somevalue3}
and an array
var arr = [name2, name3]
Both are dynamically created.
I need to filter object by array(exactly by property names, not by its values).
But so far all methods I've found are about filter by values.
So result should be
var result = {name2: somevalue2, name3: somevalue3}
I'm using angular, underscore. I need to filter it not in template, but in controller.
I appreciate any help!
A:
You can use _.pick to "filter" the object.
var obj = { name1: "somevalue1", name2: "somevalue2", name3: "somevalue3"};
var keys = ["name1", "name2"];
console.log(_.pick(obj, keys));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
|
[
"stackoverflow",
"0036604375.txt"
] |
Q:
jqgrid- applying multiple themes to multiple table in the same page
I have 2 jqgrid tables here in fiddle, what is the best way to apply multiple themes only to the jqgrid tables.
I had tried adding css selector scope to the tables but it didnt work correctly on the table http://jqueryui.com/download/
Theme1 for table1
<link rel="stylesheet" type="text/css" href="../themeLefrog/jquery-ui.theme.css" />
<link rel="stylesheet" type="text/css" href="../themeLefrog/jquery-ui.min.css" />
<link rel="stylesheet" type="text/css" href="../themeLefrog/jquery-ui.theme.css" />
My theme2 for table2
<link rel="stylesheet" type="text/css" href="../themeBlitzer/jquery-ui.theme.css" />
<link rel="stylesheet" type="text/css" href="../themeBlitzer/jquery-ui.min.css" />
<link rel="stylesheet" type="text/css" href="../themeBlitzer/jquery-ui.theme.css" />
A:
First of all you should download custom jQuery UI themes from the jQuery UI download page. For example, you want to use Le-Frog and Redmond themes on one HTML page. The you can use HTML code like
<div class="redmond">
<table id="grid1"></table>
</div>
<div class="le-frog">
<table id="grid2"></table>
</div>
It means that div.redmond and div.le-frog could be selectors, which could be used to specify the scope of applying of the corresponding jQuery UI Theme CSS. Thus you can choose the following on the download page:
You included both CSS on your web page, like
<link rel="stylesheet" href="jquery-ui/le-frog/jquery-ui.css">
<link rel="stylesheet" href="jquery-ui/redmond/jquery-ui.css">
and use the same code as usual. The results will be like on the demo:
or like on the another demo, which use Blitzer and Le-Frog themes:
I included in the demos jquery-ui.css instead of jquery-ui.min.css only to simplify everybody to examine the files. There contains CSS rules with the corresponding rules. For example
div.redmond .ui-widget {
font-family: Lucida Grande,Lucida Sans,Arial,sans-serif;
font-size: 1.1em;
}
and
div.le-frog .ui-widget {
font-family: Lucida Grande,Lucida Sans,Arial,sans-serif;
font-size: 1.1em;
}
instead of the standard rule
.ui-widget {
font-family: Lucida Grande,Lucida Sans,Arial,sans-serif;
font-size: 1.1em;
}
|
[
"stackoverflow",
"0051892386.txt"
] |
Q:
OuputCache, is there any way to differenciate between logged in and anonymous users
I have an MVC .net site and I am attempting to leverage OutputCache for performance gain.
/// <summary>
/// Broker View Page
/// </summary>
/// <returns></returns>
[Route("{lang}/brokers/details/{id}/{code}", Order = 1)]
[Route("brokers/details/{id}/{code}", Order = 2)]
[OutputCache(Duration = (60 * 60), VaryByParam = "none")]
public ActionResult View(int? id, string code)
{
This delivers a huge performance gain on 2nd and subsequent visits to a site, but I have just discovered one huge Gotcha!
If a client visits the page anonymously, subsequently logs in and returns to the page, they are still served up the unauthenticated view (authenticated clients should see the same content, but different header)
is there any way I can use OutputCache to keep my performance gain, but have it smart enough to know about authenticated/unauthenticated differences?
A:
You can use "VaryByCustom"
In controller
[OutputCache(Duration = 1000, VaryByCustom = "user")]
public ActionResult Index()
{
return View();
}
In Global.ascx.cs :
public override string GetVaryByCustomString(HttpContext context, string custom)
{
if (custom == "user")
{
if (context.Request.IsAuthenticated)
{
return context.User.Identity.Name;
}
}
return "anonymous"
}
Each user gets their own unique cached version version and there is a cached version created for "anonymous" users too.
|
[
"stackoverflow",
"0009001294.txt"
] |
Q:
Bubble sort implementation in PHP?
I need to do a bubble sort algorithm in PHP.
I want to know whether any one has any good examples that I can use, or an open source library which can do this.
I have a few spaces in a set (array), i want to fill these spaces with object (a person), so no space can have a male and a female, this why i am trying to find out a bubble sort algorithm.
My plan is to fill in any of the available spaces regardless of the gender, and after that sort them separately.
Thanks.
A:
function bubble_sort($arr) {
$size = count($arr)-1;
for ($i=0; $i<$size; $i++) {
for ($j=0; $j<$size-$i; $j++) {
$k = $j+1;
if ($arr[$k] < $arr[$j]) {
// Swap elements at indices: $j, $k
list($arr[$j], $arr[$k]) = array($arr[$k], $arr[$j]);
}
}
}
return $arr;
}
For example:
$arr = array(1,3,2,8,5,7,4,0);
print("Before sorting");
print_r($arr);
$arr = bubble_sort($arr);
print("After sorting by using bubble sort");
print_r($arr);
A:
Using bubble sort is a very bad idea. It has complexity of O(n^2).
You should use php usort, which is actually a merge sort implementation and guaranteed O(n*log(n)) complexity.
A sample code from the PHP Manual -
function cmp( $a, $b ) {
if( $a->weight == $b->weight ){ return 0 ; }
return ($a->weight < $b->weight) ? -1 : 1;
}
usort($unsortedObjectArray,'cmp');
A:
$numbers = array(1,3,2,5,2);
$array_size = count($numbers);
echo "Numbers before sort: ";
for ( $i = 0; $i < $array_size; $i++ )
echo $numbers[$i];
echo "n";
for ( $i = 0; $i < $array_size; $i++ )
{
for ($j = 0; $j < $array_size; $j++ )
{
if ($numbers[$i] < $numbers[$j])
{
$temp = $numbers[$i];
$numbers[$i] = $numbers[$j];
$numbers[$j] = $temp;
}
}
}
echo "Numbers after sort: ";
for( $i = 0; $i < $array_size; $i++ )
echo $numbers[$i];
echo "n";
|
[
"stackoverflow",
"0018877243.txt"
] |
Q:
Why FFmpeg print SAR instead of PAR?
If my knowledge is correct, SAR (Storage Aspect Ratio) is the ratio of pixel dimensions.
For example, a 640 × 480 video has a SAR of 640/480 = 4:3.
Whereas PAR (Pixel Aspect Ratio) is ratio of pixel height and width, and most of modern videos have square PAR (1:1).
But when I tried to check it with ffmpeg -i I got square SAR instead of square PAR for all test videos.
Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1280x720 [SAR 1:1 DAR 16:9], 1758 kb/s, 24.99 fps, 25 tbr, 25 tbn, 50 tbc
Stream #0:0(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 540x360 [SAR 1:1 DAR 3:2], 386 kb/s, 25 fps, 25 tbr, 25 tbn, 50 tbc
Stream #0:0(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 450x360 [SAR 1:1 DAR 5:4], 328 kb/s, 25 fps, 25 tbr, 25 tbn, 50 tbc
Is it ffmpeg bug or my mistake?
A:
As it turned out, ffmpeg uses different notations
SAR for Sample Aspect Ratio
DAR for Display Aspect Ratio
A:
SAR (Sample Aspect Ratio) is the same as PAR (Pixel Aspect Ratio).
These two terms are used interchangeably. They mean the ratio between the width and the height of individual pixels.
In contrast, DAR (Display Aspect ratio) is the ratio between the width and the height of the full image.
Notes:
SAR - All modern devices have it 1:1; old devices - mainly from the analogic-numeric transition era - used non-square pixels.
DAR - examples: For SVGA it is 4:3, for QWXGA it is 16:9.
|
[
"stackoverflow",
"0042881956.txt"
] |
Q:
Classification HMM gyroscope data Jahmm Can't learn model
I'm training HMMs implemented in JaHMM with sensor data from an accelerometer and a gyroscope obtained from an Android wearable.
The HMM trained with accelerometer data outputs fine learned states, and has a somewhat acceptable error rate.
Both HMM's is initialized as follows:
Hmm<ObservationVector> hmm = new Hmm<>(2, new OpdfMultiGaussianFactory(3));
hmm.setPi(0, 0.5);
hmm.setPi(1, 0.5);
hmm.setOpdf(0, new OpdfMultiGaussian(
new double[]{0,0,0},
new double[][] {{0.1,0,0},
{0,0.1,0},
{0,0,0.1}
}));
hmm.setOpdf(1, new OpdfMultiGaussian(
new double[]{0,0,0},
new double[][] {{0.1,0,0},
{0,0.1,0},
{0,0,0.1}
}));
hmm.setAij(0, 0, 0.5);
hmm.setAij(0, 1, 0.5);
hmm.setAij(1, 0, 0.5);
hmm.setAij(1, 1, 0.5);
Output for HMM trained with accelerometer data:
HMM with 2 state(s)
State 0
Pi: 0.5000000000000188
Aij: 0.5 0.5
Opdf: Multi-variate Gaussian distribution --- Mean: [ 0.036 -0.051 0.075 ]
State 1
Pi: 0.5000000000000188
Aij: 0.5 0.5
Opdf: Multi-variate Gaussian distribution --- Mean: [ 0.036 -0.051 0.075 ]
However, the HMM trained with gyroscope data can't seem to learn the states of the HMM no mater how many training iterations I've tried (500 iterations). The e.g. learned state probabilities is just NaN
Output for HMM trained with gyroscope data:
HMM with 2 state(s)
State 0
Pi: NaN
Aij: ? ?
Opdf: Multi-variate Gaussian distribution --- Mean: [ ? ? ? ]
State 1
Pi: NaN
Aij: ? ?
Opdf: Multi-variate Gaussian distribution --- Mean: [ ? ? ? ]
What could be the cause for this behavior? Is there a preprocessing or normalize step i need to perform before the data is usable in the HMM?
Is the number of states in the HMM that is insufficient? I've tried with five states, but it yields the same result.
A snippet of the training file for accelerometer can be seen here:
https://gist.github.com/Gudui/91d2c6b2452f1ea6a5c925b1eed9b40c
A snippet of the training file for gyroscope can be seen here:
https://gist.github.com/Gudui/987cc1c1a7c0311a03988b818e7cbbcb
For both training files, each line represent a training sequence.
The library is available here: https://github.com/tanjiti/jahmm
Thanks in advance!
A:
Elaborating my comment, I suggest:
Use random initialization of the Gaussian pdf, that is instead of initializing the means vector to [0,0,0], and the covariance matrix to 0.1 times the identity matrix, as you do now, use some random values or some empirical mean and covariance based on your data.
Whiten your data, that is make sure it has zero mean and unit variance in each coordinate (or even use PCA to make the coordiantes uncorrelated.
|
[
"stackoverflow",
"0049437435.txt"
] |
Q:
My struct isn't working for decodable
been using swift 3 for sometime, till i updated my Xcode which came with swift 4, and with that i had to start using encodable decodable , but i'm having a hard time generating structs to decode. This is the json i'm trying to turn into an object
{
"status": "true",
"message": "Valid request",
"data": {
"user_id": "16",
"first_name": "Hamidouh",
"last_name": "Semix",
"other_name": null,
"fullname": "Hamidouh Semix",
"alias": null,
"about": "",
"sex_id": "1",
"sex": "Male",
"birth_date": "1989-08-17 00:00:00",
"relation_status_id": null,
"relation_status": null,
"relation_user_id": null,
"relation_user_first_name": null,
"relation_user_last_name": null,
"relation_user_fullname": null,
"location": null,
"contact": null,
"profile_pic": "698",
"profile_folder_name": "profile-picture",
"profile_pic_filename": "PROFILE-IMG-UPLOAD-1-16-20171222101217.jpg",
"cover_pic": "697",
"cover_folder_name": "cover-picture",
"cover_pic_filename": "COVER-IMG-UPLOAD-1-16-20171222100128.png",
"followers_list": {
"user_11": {
"id": "11",
"datetime": "2018-02-20 19:09:44"
}
},
"following_list": {
"user_1": {
"id": "1",
"datetime": "2018-03-01 09:53:24"
},
"user_3": {
"id": "3",
"datetime": "2018-02-19 09:18:18"
},
"user_24": {
"id": "24",
"datetime": "2017-12-22 09:58:17"
},
"user_260": {
"id": "260",
"datetime": "2018-02-19 09:18:16"
}
},
"mutual_list": {
"user_78": {
"id": "78",
"datetime": "2017-12-08 12:05:23"
}
},
"request_counter": "0",
"dream_destination_list": null,
"hidden_content_list": null,
"email": "[email protected]",
"username": null,
"password": "84bcec2f89a4f8cdd17b4a98d1a6cbf69bc9efe657d36a09b2d423fa3030772ab8ba9e24",
"salt": "owkLO",
"social_media_auth": null,
"social_media_id": null,
"date_created": "2017-08-18 14:00:22",
"last_seen": "2018-03-16 13:53:57",
"is_suspended": null,
"is_notified": null,
"approve_token": "8f82fbac62ded7260a3faa45460719a1390e3e216c6ebf3c4794f2da627138b9",
"device_token": null,
"language_id": null,
"language_machine_name": null,
"language_label": null,
"active": "1"
}
}
currently these are the structs i've been able to generate for above json
struct user : Decodable {
let status: String
let message: String
let data: userData
}
struct userData : Decodable {
let user_id: Int
let first_name: String
let last_name: String
let other_name: String
let fullname: String
let alias: String
let about: String
let sex_id: Int
let sex: String
let birth_date: String
let relation_status_id: Int
let relation_status: String
let relation_user_id: Int
let relation_user_first_name: String
let relation_user_last_name: String
let relation_user_fullname: String
let location: String
let contact: String
let profile_pic: Int
let profile_folder_name: String
let profile_pic_filename: String
let cover_pic: Int
let cover_folder_name: String
let cover_pic_filename: String
let followers_list: Int
let following_list: Int
let mutual_list: Int
let request_counter: Int
let dream_destination_list: Int
let hidden_content_list: Int
let email: String
let username: String
let password: String
let salt: String
let social_media_auth: String
let social_media_id: Int
let date_created: String
let last_seen: String
let is_suspended: String
let is_notified: String
let approve_token: String
let device_token: String
let language_id: Int
let language_machine_name: String
let language_label: String
let active: Int
}
This is the decoding code i've written to try and parse this
//send request to server
guard let loginUrl = URL(string: "https://xxxxxx.com/api/index.php/Auth/login") else {return}
//request url
var request = URLRequest(url: loginUrl)
// method to pass data
request.httpMethod = "POST"
let body = "username=\(usernameVar)&password=\(passwordVar)"
request.httpBody = body.data(using: String.Encoding.utf8)
//launch session
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
guard let data = data else {return}
do {
//let json = try JSONSerialization.jsonObject(with: data, options: [])
//print(json)
let userDetails = try JSONDecoder().decode(user.self, from: data)
for details in userDetails {
print(details.message)
}
}catch{
print(error)
}
}
task.resume()
This is the error
typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))
A:
You should change your error message to a more helpful error message Lol.
You haven't accounted for optional values in your json. Remember there is a difference between String and String? there are several values in your json payload that return nil. In your swift struct you need to mark those fields as Optionals.
You also have mismatched Types. All of your returned types are String or String? not Int. Those are just numbers returned as String?. There are also Dictionary types nested in this payload as well. The followers_list is a dictionary so you need to make a new struct with those properties, called List and in your UserData struct, set the type of those "lists" to [String:List]
Also when you're confused about what kind of error is being thrown while decoding, (and most of the CocoaTouch Framework) those are NSErrors. You can print the value of the error to the console and it'll tell you exactly what error is exiting the scope. IE:
valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [__lldb_expr_20.user.(CodingKeys in _992B1F7B4C3E0BAC48AEA280B9410D72).data, __lldb_expr_20.userData.,
debugDescription: "Expected String value but found null instead.", underlyingError: nil))
The above error message tells you that CodingKey...userData was set to expect a String but there was null (nil).
Heres what your current struct should look like:
struct User : Decodable {
let status: String
let message: String
let data: userData
}
struct List: Decodable {
var id: String?
var datetime: String?
}
struct UserData : Decodable {
let user_id: String
let first_name: String
let last_name: String
let other_name: String?
let fullname: String
let alias: String?
let about: String
let sex_id: String
let sex: String
let birth_date: String
let relation_status_id: String?
let relation_status: String?
let relation_user_id: String?
let relation_user_first_name: String?
let relation_user_last_name: String?
let relation_user_fullname: String?
let location: String?
let contact: String?
let profile_pic: String
let profile_folder_name: String
let profile_pic_filename: String
let cover_pic: String
let cover_folder_name: String
let cover_pic_filename: String
let followers_list: [String:List]
let following_list: [String:List]
let mutual_list: [String:List]
let request_counter: String
let dream_destination_list: List?
let hidden_content_list: List?
let email: String
let username: String?
let password: String?
let salt: String
let social_media_auth: String?
let social_media_id: String?
let date_created: String
let last_seen: String
let is_suspended: String?
let is_notified: String?
let approve_token: String
let device_token: String?
let language_id: String?
let language_machine_name: String?
let language_label: String?
let active: String
}
Loose the snake case and use CodingKeys to follow Swift Naming Conventions or use a public struct with the values you care about(You don't have to model the entire JSON payload) with a private struct that models the JSON and set the values with a custom init(from decoder: Decoder) using this answer.
|
[
"expatriates.stackexchange",
"0000013214.txt"
] |
Q:
What does a non-EU citizen (German residence permit holder) require to live in the Netherlands?
I am a non-EU citizen and work for a German company. We currently have a project in the Netherlands. I have a residence permit for Germany, and I would now like to get a BSN for the Netherlands, as I would be living there for extended periods. Am I eligible, or do I need to get a Dutch work permit? Mind you, I am employed in Germany and not the Netherlands. My passport is Australian.
A:
If you live in the Netherlands, you almost certainly need a Dutch work and residence permit (the one exception that comes to mind is posted work but that's apparently not your status). The fact you are employed by a German company in Germany only makes formalities more complex but does not in itself exempt you from this basic requirement, which stems from the objective fact that you are residing there.
You can get a BSN has a non-resident but that's moot, even if you somehow managed to live in the Netherlands without one (which would make interaction with all public services difficult), you would still need a residence permit.
|
[
"superuser",
"0000297158.txt"
] |
Q:
How to recover a server stuck with a bad IP address ? (NSLU2)
I have a NSLU2 (debian server) that was configured for an old network, with a static IP address on Ethernet.
Now I've moved, and the server boots using the old IP address, so I can't access it when I connect it to my router with Ethernet, or even when I connect it to my PC via Ethernet.
I don't remember what was its old IP address, I tried 192.168.0.1/2/3/4 and 192.168.1.1/2/3/4 but no response to the ping (I'm pretty sure the old address was in there).
How can I change the IP address, or ssh to it now ? The debian system is installed on a USB stick, is there a file that I can edit on my computer to make it start ok ?
A:
Load up wireshark and monitor the network until you see a packet coming from the server. Hopefully there is some service such as DNS or NTP that will trigger a network query. You can go through the packet list for any unknown IP addresses - that will probably be the server IP address.
|
[
"ru.stackoverflow",
"0000485272.txt"
] |
Q:
Как вывести TimePickerDialog, соответствующий формату времени в системе (12/24 часа)?
Как создать универсальный TimePickerDialog, чтобы сам определял формат времени.
Если на телефоне установлено время в 24-часовом формате, то просит при добавлении времени в TimePickerDialog в 24-часовом формате - (11:50), если в 12-часовом, то в 12-часовом просит - (11:50 AM)
A:
Формат времени устройства проверяется с помощью
DateFormat.is24HourFormat(context)
Полученный результат можно использовать в конструкторе TimePickerDialog
public TimePickerDialog (Context context, TimePickerDialog.OnTimeSetListener
callBack, int hourOfDay, int minute, boolean is24HourView)
или TimePicker:
yourTimePicker.setIs24HourView(DateFormat.is24HourFormat(context))
|
[
"stackoverflow",
"0048996157.txt"
] |
Q:
Python - using a non-integer number instead of an integer
I am trying to write some code in python for data segmentation, here is my code
it consists of two functions. I used python 3.5
def windowz(data, size):
start = 0
while start < len(data):
yield start, start + size
start += (size / 2)
def segment_dap(x_train,y_train,window_size):
segments = np.zeros(((len(x_train)//(window_size//2))-1,window_size,9))
labels = np.zeros(((len(y_train)//(window_size//2))-1))
i_segment = 0
i_label = 0
for (start,end) in windowz(x_train,window_size):
if(len(x_train[start:end]) == window_size):
m = stats.mode(y_train[start:end])
segments[i_segment] = x_train[start:end]
labels[i_label] = m[0]
i_label+=1
i_segment+=1
return segments, labels
input_width = 23
if dataset =="dap":
print ("dap seg")
input_width = 25
print ("segmenting signal...")
train_x, train_y = segment_dap(x_train,y_train,input_width)
test_x, test_y = segment_dap(x_test,y_test,input_width)
print ("signal segmented.")
but this code gives me the following warning
Warning (from warnings module):
File "C:\Users\hp\Downloads\Deep-Learning-for-Human-Activity-Recognition-master\ModelCreation\RNN\FFLSTM\fflstm.py", line 37
if(len(x_train[start:end]) == window_size):
VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
Warning (from warnings module):
File "C:\Users\hp\Downloads\Deep-Learning-for-Human-Activity-Recognition-master\ModelCreation\RNN\FFLSTM\fflstm.py", line 38
m = stats.mode(y_train[start:end])
VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
Warning (from warnings module):
File "C:\Users\hp\Downloads\Deep-Learning-for-Human-Activity-Recognition-master\ModelCreation\RNN\FFLSTM\fflstm.py", line 39
segments[i_segment] = x_train[start:end]
VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
A:
(size / 2) in:
def windowz(data, size):
start = 0
while start < len(data):
yield start, start + size
start += (size / 2)
Will give you a float. You can force it be an integer with:
(size // 2)
|
[
"stackoverflow",
"0037229450.txt"
] |
Q:
A faster function to lower the resolution of a raster R
I am using the raster package to lower the resolution of big rasters, using the function aggregate like this
require(raster)
x <- matrix(rpois(1000000, 2),1000)
a <-raster(x)
plot(a)
agg.fun <- function(x,...)
if(sum(x)==0){
return(NA)
} else {
which.max(table(x))
}
a1<-aggregate(a,fact=10,fun=agg.fun)
plot(a1)
the raster images I have to aggregate are much bigger 34000x34000 so I would like to know if there is a faster way to implement the agg.fun function.
A:
You can use gdalUtils::gdalwarp for this. For me, it's less efficient than @JosephWood's fasterAgg.Fun for rasters with 1,000,000 cells, but for Joseph's larger example it's much faster. It requires that the raster exists on disk, so factor writing time into the below if your raster is in memory.
Below, I've used the modification of fasterAgg.Fun that returns the most frequent value, rather than its index in the block.
library(raster)
x <- matrix(rpois(10^8, 2), 10000)
a <- raster(x)
fasterAgg.Fun <- function(x,...) {
myRle.Alt <- function (x1) {
n1 <- length(x1)
y1 <- x1[-1L] != x1[-n1]
i <- c(which(y1), n1)
x1[i][which.max(diff(c(0L, i)))]
}
if (sum(x)==0) {
return(NA)
} else {
myRle.Alt(sort(x, method="quick"))
}
}
system.time(a2 <- aggregate(a, fact=10, fun=fasterAgg.Fun))
## user system elapsed
## 67.42 8.82 76.38
library(gdalUtils)
writeRaster(a, f <- tempfile(fileext='.tif'), datatype='INT1U')
system.time(a3 <- gdalwarp(f, f2 <- tempfile(fileext='.tif'), r='mode',
multi=TRUE, tr=res(a)*10, output_Raster=TRUE))
## user system elapsed
## 0.00 0.00 2.93
Note that there is a slight difference in the definition of the mode when there are ties: gdalwarp selects the highest value, while the functions passed to aggregate above (via which.max's behaviour) select the lowest (e.g., see which.max(table(c(1, 1, 2, 2, 3, 4)))).
Also, storing the raster data as integer is important (when applicable). If the data are stored as float (the writeRaster default), for example, the gdalwarp operation above takes ~14 sec on my system. See ?dataType for available types.
A:
Try this:
fasterAgg.Fun <- function(x,...) {
myRle.Alt <- function (x1) {
n1 <- length(x1)
y1 <- x1[-1L] != x1[-n1]
i <- c(which(y1), n1)
which.max(diff(c(0L, i)))
}
if (sum(x)==0) {
return(NA)
} else {
myRle.Alt(sort(x, method="quick"))
}
}
library(rbenchmark)
benchmark(FasterAgg=aggregate(a, fact=10, fun=fasterAgg.Fun),
AggFun=aggregate(a, fact=10, fun=agg.fun),
replications=10,
columns = c("test", "replications", "elapsed", "relative"),
order = "relative")
test replications elapsed relative
1 FasterAgg 10 12.896 1.000
2 AggFun 10 30.454 2.362
For a larger test object, we have:
x <- matrix(rpois(10^8,2),10000)
a <- raster(x)
system.time(a2 <- aggregate(a, fact=10, fun=fasterAgg.Fun))
user system elapsed
111.271 22.225 133.943
system.time(a1 <- aggregate(a, fact=10, fun=agg.fun))
user system elapsed
282.170 24.327 308.112
If you want the actual values as @digEmAll says in the comments above, simply change the return value in myRle.Alt from which.max(diff(c(0L, i))) to x1[i][which.max(diff(c(0L, i)))].
A:
Just for fun I created also an Rcpp function (not much faster than @JosephWood) :
########### original function
#(modified to return most frequent value instead of index)
agg.fun <- function(x,...){
if(sum(x)==0){
return(NA)
} else {
as.integer(names(which.max(table(x))))
}
}
########### @JosephWood function
fasterAgg.Fun <- function(x,...) {
myRle.Alt <- function (x1) {
n1 <- length(x1)
y1 <- x1[-1L] != x1[-n1]
i <- c(which(y1), n1)
x1[i][which.max(diff(c(0L, i)))]
}
if (sum(x)==0) {
return(NA)
} else {
myRle.Alt(sort(x, method="quick"))
}
}
########### Rcpp function
library(Rcpp)
library(inline)
aggrRcpp <- cxxfunction(signature(values='integer'), '
Rcpp::IntegerVector v(clone(values));
std::sort(v.begin(),v.end());
int n = v.size();
double sum = 0;
int currentValue = 0, currentCount = 0, maxValue = 0, maxCount = 0;
for(int i=0; i < n; i++) {
int value = v[i];
sum += value;
if(i==0 || currentValue != value){
if(currentCount > maxCount){
maxCount = currentCount;
maxValue = currentValue;
}
currentValue = value;
currentCount = 0;
}else{
currentCount++;
}
}
if(sum == 0){
return Rcpp::IntegerVector::create(NA_INTEGER);
}
if(currentCount > maxCount){
maxCount = currentCount;
maxValue = currentValue;
}
return wrap( maxValue ) ;
', plugin="Rcpp", verbose=FALSE,
includes='')
# wrap it to support "..." argument
aggrRcppW <- function(x,...)aggrRcpp(x);
Benchmark :
require(raster)
set.seed(123)
x <- matrix(rpois(10^8, 2), 10000)
a <- raster(x)
system.time(a1<-aggregate(a,fact=100,fun=agg.fun))
# user system elapsed
# 35.13 0.44 35.87
system.time(a2<-aggregate(a,fact=100,fun=fasterAgg.Fun))
# user system elapsed
# 8.20 0.34 8.59
system.time(a3<-aggregate(a,fact=100,fun=aggrRcppW))
# user system elapsed
# 5.77 0.39 6.22
########### all equal ?
all(TRUE,all.equal(a1,a2),all.equal(a2,a3))
# > [1] TRUE
|
[
"history.stackexchange",
"0000028787.txt"
] |
Q:
How do nations maintain sovereignty over conquered nations?
After the battle of Hastings, William defeated the English with ~7000 men. What I don't understand fully, is how an army of 7000 can maintain control over England, which had around 1.7 million people living there at the time. Perhaps this is not the best question, since William did have a claim to the throne.
What I'm asking essentially is, how did nations control other conquered nations when the armies they had were fractions of the actual populations of the conquered nations.
A:
There is a difference between "control" and sovereignty. After the Battle of Hastings it was clear William had the most powerful force, so he became sovereign. When he marched to London there was noone to oppose him, so the town capitulated to him. He took hostages in London and then went around demonstrating his power. This activity which took place for about two months between the middle of October and December 1066 is not well documented, but apparently he went in a circle around London killing, burning and pillaging as he went while various small local forces made sporadic resistance.
As this happened Edgar Ætheling was declared king by a Saxon Witenaġemot and so it became a sort of race against time as William tried to get local lords to pledge fealty to him before any kind of serious resistance could be formed against him. During this period of chaos his army made many massacres to discourage resistance. Eventually, late in December, the Archbishop and the nobles in the London area decided to crown William King.
Even after he was king in Westminster, there were many petty revolts and insubordination all throughout England to his rule and William spent years marching around subduing different people and places and building castles to enforce his rule. In many cases the forces in these castles were tiny compared to the local population, but their armor and weapons made it no easy matter to kill them.
In cases where a garrison was wiped out or there was serious resistance from a lord, William would march with an army to defeat it. Such expeditions were always extremely punitive. The army would kill everyone and burn anything they could to punish the local people for resisting. Such actions often created large numbers of refugees, fleeing for their lives. During this time Scotland actually gained a significant amount of population, just from refugees who were fleeing the conflict in England.
To answer your question in general: a military force acts as a coordinated team and coupled with powerful weapons it is difficult for lightly armed, unorganized people to contest. If all of England had gathered together, financed an army and organized themselves into a fighting unit they might have been able to defeat William, but they failed to do this. Do not underestimate the power of a military unit. For example, Cortez, with only about 120 men, conquered a civilization in which he battled against thousands of men all gathered against him. If you read the account of Cortez given by Bernal Diaz, one of his lieutenants, you will get an idea of how a tiny band of men who are well armed and coordinated can defeat much larger forces.
A:
There may have been 1.7 million people in England, but
50% were women, who were non-combatants, so we're down to 0.8m (arguably; scaly llama exceptions apply)
33% of the remainder were over fighting age and 33% below fighting age; we're down to just over 0.2M
Of the remainder, probably 95% of them had no military training (remember that Harold Godwinson had marched all the viable troops to the east to fight Hardrada, then South to fight William the Bastard.) The guys were were not summoned into the levee, were not, to put it gently, the "A team". if they had weapons, the weapons are crap, and most of them have never actually struck a blow in hot anger. We're down to about 70,000 people at this point.
90% of the remainder were unwilling to leave their local area (<25miles squared)
90% of all the inhabitants, hated some other (local) tribe more than they hated the conquerors; the conquerors are distant and can be ignored. Olaf is local, obnoxious, smells funny and has been making funny eyes at both my daughters and my goats. I need to kill Olaf before I wander about the countryside killing Normans who I've never met.
We're down to under 100 combatants who might have been motivated to resist.
Asymmetrical warfare is less effective against a force that is willing to countenance genocide.
William and his cronies were professional warriors with weapons, training, armor, training, horses, training, and experience. Training is probably at least a 3:1 advantage; weapons and armor at least another 2:1 advantage. Horses probably 2:1 again. Remember that Napoleon said that logistics is a 9:1 advantage. Militia has no logistics outside the county; William takes whatever he wants and he has extensive experience in logistics.
If by some chance a villager were to wound a Norman, the Normans could burn the village down and kill every inhabitant. It is perfectly legal for William to kill a peasant; it is not just illegal to resist a Norman, but it will probably also damn your soul to eternal hell.
None of the numbers above are right- they're just to illustrate the reasons why conquering armies only need to be tiny.
A:
A more "normal" ratio of military to population might be something like 1%. That ratio would imply 17,000 men for the Norman conquerers instead of 7,000.
There was one other factor in the Normans' favor. In modern times, guns are a great "equalizer." Not "everyone," but a large part of the population can be taught to use a gun in a short period of time. During World War II, the Russians (and later the Germans) sent teenaged boys into battle with only a few days' training in basic weapons management.
The "hand" weapons of the time took years, not days, to master. One trained man with armor and skill with a "regulation" weapon was easily the match of five or even ten untrained men with crude weapons and no armor. This inequality meant that the Normans could maintain control with even less than 1% of the population. And it was also true that the Normans were better and more heavily armed than Harold's "Anglo-Saxons" that they had just defeated.
|
[
"stackoverflow",
"0001025941.txt"
] |
Q:
Any way to detect whether the pointer points to array?
Is there any way to detect, whether the pointer points to array in C++? My problem is that I want to implement a class, that becomes the owner of the array. My class is initialized with the pointer and I would like to know, whether the pointer is really an array pointer. Here is the simplified code:
class ArrayOwner {
public:
explicit ArrayOwner( int* initialArray ) : _ptrToArray(initialArray) {}
virtual ~ArrayOwner() { delete [] _ptrToArray; }
private:
int* _ptrToArray;
}
This usage will be ok: ArrayOwner
foo( new int[10] );
But this usage
leads to undefined behaviour:
ArrayOwner foo( new int() );
I would like to add assert in the constructor, that the "initialArray" pointer is really an array pointer. I cannot change the contract of the constructor, use vectors e.t.c. Is there any way to write this assert in C++?
A:
No, unfortunately not. C++ RTTI does not extend to primitive types.
A:
There's no portable way to do it.
A:
It looks like a bad design to me. Don't separate new and delete this way.
The array should be allocated in the object constructor, not passed as a parameter.
Memory management in C++ is hard, don't make it harder with bad practice like this.
|
[
"stackoverflow",
"0038573236.txt"
] |
Q:
How to inject DbContext in a custom localization provider in ASP.NET Core?
As explained in the asp.net core docs you can configure a custom provider for request localization. As stated in the docs:
Suppose you want to let your customers store their language and culture in your databases. You could write a provider to look up these values for the user.
For that the following code snippet is provided in the docs and also in the github sample Localization.StarterWeb:
services.Configure<RequestLocalizationOptions>(options => {
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("fr")
};
options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
{
// My custom request culture logic
// DbContext needed here <--
return new ProviderCultureResult("en");
}));});
Can anybody explain me how to inject a DbContext to load the user specific language from DB in the above function?
A:
Well, you can't inject it via constructor because you need to instantiate it during ConfigureServices method and the container isn't available at this point.
Instead you can resolve via HttpContext.
public class CustomRequestCultureProvider : RequestCultureProvider
{
// Note we don't inject any dependencies into it, so we can safely
// instantiate in ConfigureServices method
public CustomRequestCultureProvider() { }
public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
var dbContext = httpContext.RequestServices
.GetService<AppDbContext>();
}
}
Be aware though that this may be less than optimal, as you'll have calls to database on every request, so maybe it's worth to abstract this further and use an caching strategy depending on what exactly you want to do with the DbContext.
Usually one should avoid database calls in culture providers, filters etc. for performance reasons
Update:
There is a generic version of GetService<T>, but you need to import the namespace via using Microsoft.Extensions.DependencyInjection;.
|
[
"math.stackexchange",
"0002194110.txt"
] |
Q:
Using chain rule to find $\frac{dz}{dt}$
I know what the chain rule is but i am unsure how to apply it to this case.
$$z=x^3\cdot e^{2y}$$
$$x=2t$$
$$y=t^2$$
Edit: Fixed title to $\frac{dz}{dt}$.
A:
Note the multivariable chain rule:
$$\frac{dz}{dt}=\frac{\partial z}{\partial x}\cdot \frac{dx}{dt}+\frac{\partial z}{\partial y}\cdot \frac{dy}{dt} \tag{1}$$
Simply evaluate the ordinary and partial derivatives, and substitute them into the equation above. You should have a result for $\frac{dz}{dt}$ in terms of $x,y$ and $t$. Then, substitute the parametrizations for $x(t)$ and $y(t)$ to obtain an expression for $\frac{dz}{dt}$ strictly in terms of $t$ as done on the first example of the link I provided.
Let's start by evaluating $\frac{\partial z}{\partial x}$. Since we must treat the variable $y$ as a constant as a result of partial differentiation, $e^{2y}$ is also treated as one. Therefore:
$$\frac{\partial z}{\partial x}=3x^2\cdot e^{2y}$$
Can you continue?
|
[
"stackoverflow",
"0006857479.txt"
] |
Q:
WCF service authentication method
I'm building a WCF SOAP service at the moment. I will, of course, need some authentication on the service.
Reading this very helpful blog post says that to use the built-in authentication points requires that the endpoint use the wsHttp binding.
This would be fine if I could guarantee that users would be communicating with the service through a client based on the meta-data exposed by WCF (basically, something like a client written in C# with a web service reference). However, I can't guarantee this!
I will still need to allow users to communicate with just raw (unencrypted) XML.
So, questions:
Does the wsHttp binding still allow for raw XML input?
If not, would I be wiser to
Implement two separate authetication points? One for raw XML input and one for encrypted input
Or
Allow input from wsHttp to fall back on some in-method validation that would be shared with the raw XML input?
Is it wise to allow users to pass their credentials inside a raw XML request?
EDIT: It sounds like I miscommunicated or misunderstood something in my original post, so here I will clarify what I mean by "raw XML".
By raw XML, I mean just the SOAP packet and the accompanying HTTP headers - as I might send from soapUI or Fiddler. As I understand it, messages over the wsHttp binding are encrypted when a client is generated from the WSDL (for example, in C#).
If this is not the case, then how would I go about attaching the same sorts of credentials to a raw XML (for want of a better term) request as I do a request run through a client? Are they attached as HTTP headers? XML elements in the SOAP envelope?
A:
wsHttp is a SOAP binding, which means that your content gets wrapped in a SOAP envelope, possibly with headers relating to the message and various WS-* specifications being used.
I would ask why you need to support raw XML? Most platforms today support SOAP messaging and the whole idea of SOAP is to provide interoperability between different platforms. On most platforms it is as easy to develop a SOAP client as a raw XML client. In most cases, it is simply a case of taking the WSDL and generating a client. If you want to use standard facilities like authentication and message encryption then this is a much better way to go.
There are currently no hooks to do interoperable authentication for raw XML. You will have to come up with your own mechanism to do this and it will be non-standard. For your web service users, this means it will be probably entail more development effort than if you just went with SOAP.
|
[
"math.stackexchange",
"0002436837.txt"
] |
Q:
Equivalence Relation Generated by the Empty Set
I'm reading David Spivak's book "Category Theory for the Sciences" and on page 79 there is a problem related to generating $S \subseteq X \times X$ the smallest equivalence relation that contains $R$.
Part c) of the problem has $R = \emptyset$ and it asks you to graph the resulting equivalence relation generated by $R$. The answer just graphs the line $x = y$ in 2 dimensions (i.e. the identity relation on $X$).
Why is the line $x = y$ the smallest equivalence relation that contains $\emptyset$?
A:
The equivalence relation (on a set $X$) generatd by $R$ is the smallest $S \subseteq X \times X$ such that:
$R \subseteq S$;
$S$ is reflexive, i.e. $\forall x \in X$, $ x S x$;
$S$ is symmetric, i.e. $\forall x, y \in X$ if $xSy$ then $y Sx$;
$S$ is transitive, i.e. $\forall x, y, z \in X$ if $xSy$ and $ySz$ then $xSz$.
Let us consider the case $R = \emptyset$. I claim that $S$ is the identity relation $=$ on $X$.
Proof:
Since $R = \emptyset$, we have $R \subseteq \, = $, i.e. the identity is a binary relation on $X$ containing $R$.
Moreover, $=$ is also reflexive, symmetric and transitive.
Therefore, the identity $=$ is a binary relation on $X$ fulfilling the conditions 1-4.
Reflexivity of $S$ implies that $xSx$ for every $x \in X$, hence $= \, \subseteq S$, i.e. the identity is included in $S$.
By minimality of $S$, we have that $S$ coincide with $=$.
|
[
"stackoverflow",
"0010495585.txt"
] |
Q:
How can I use a custom subclass of a Swing component? Do I need to install it to palette?
How can I add NewJPanel, a Netbeans generated class which extends JPanel, to the palette for the GUI builder?
The goal is to be able to add a NewJPanel through the palette so that it has type NewJPanel rather than type JPanel. However, it's not available through the palette as I would expect.
I'm following:
To install via Palette Manager
Open the Palette Manager from main menu: Tools | Palette Manager | Swing/AWT Components
In the Palette Manager press button according to where the component comes from. The choices are:
from an external JAR file
from a library defined in the IDE (always create a library if the components need more than one JAR)
from a NetBeans project
from the Netbeans FAQ's.
This method doesn't work because the classes just aren't available for selection.
However, I was able to drag NewJPane onto the design view of NewJFrame where it was declared with the correct type of NewJPane (and not JPane).
A:
You can add your custom component to the matisse GUI palatte.
Build your project so the class file you want to use is part of the jar file
Open a java class that has a form, and switch to design mode. 3, Right click in the palatte and choose "palatte manager".
Choose the "add from jar" button to select your jar.
Choose the class you made, and add it to your palatte.
Now your panel is known to netbeans, and you can drag it into new panels.
|
[
"stackoverflow",
"0000749827.txt"
] |
Q:
How do I time a program executing in Windows?
I want to be able to do the Windows equivalent of this Unix/Linux command:
time fooenter code here
foo
x cpu time
y real time
z wallclock time
A:
timeit from the Windows Server 2003 Resource Kit should do the trick.
|
[
"stackoverflow",
"0039520172.txt"
] |
Q:
Safely perform changes to NSMutableArray
What can cause an assignment or change to an NSMutableArray to crash?
I have a mutable array containing custom objects, and I consistently keep no more than the 3 latest objects in it, the rest are removed. I started calling
[myArray insertObject:newObject atIndex:0];
if (myArray.count > 3)
[myArray removeLastObject]; // Crash
But whenever I do this too fast, the last line causes an exception-less crash.
I know that you are not allowed to add or remove objects of an array while it is being enumerated, but I do not enumerate myArray anywhere unless calling count on it performs an implicit enumeration. I also tried doing this:
NSMutableArray *tmp = [myArray mutableCopy];
[tmp removeLastObject];
myArray = tmp; // Crash
But the same thing happens, it crashes on the last line. Again, this works perfectly fine when doing it slowly. The action itself is being called when a user taps a button, and when tapping it too fast, it crashes every time.
EDIT:
I should add that all of this is being run inside the cellForItemAtIndexPath method of a UICollectionView.
A:
First, could you please post the crash message. It would be nice to know what error you are actually seeing.
I wonder what would happen if you switched to immutable arrays. Switch myArray to being an NSArray * and use the following.
myArray = [self updatedArray:myArray withObject:newObject];
Where -updatedArray:withObject: is
- (NSArray *)updatedArray:(NSArray *)array withObject:(id)object {
switch (array.count) {
case 0: return @[object];
case 1: return @[object, array[0]];
default: return @[object, array[0], array[1]];
}
}
Or better for testing
NSArray *temp = [self updatedArray:myArray withObject:newObject];
myArray = temp; // I assume the crash will be here!
If the code crashed at my comment, then deallocating myArray is causing the crash. My guess is that one of the items in the array is pointing to bad memory (a zombie or some such thing).
|
[
"stackoverflow",
"0045070902.txt"
] |
Q:
How can I get start date and end date of each period in sql?
I have table rows like this.
status start end
32 1/1/2017 1/2/2017
32 1/2/2017 4/2/2017
1 4/2/2017 6/3/2017
1 6/3/2017 9/5/2017
32 9/5/2017 19/5/2017
32 19/5/2017 22/6/2017
And I wanna group rows to
status start end
32 1/1/2017 4/2/2017
1 4/2/2017 9/5/2017
32 9/5/2017 22/6/2017
How can I do using SQL?
thank you for all help.
A:
I don't think you can easily do this one in one step. Maybe if you resort to some ugly recursive CTE or a very long chain of CTEs or nested sub-queries. Basically you need to reconfigure your dataset so you can tell the beginning and end of a period.
Assumptions:
Any gap means a period is ending and a new period is beginning
There are no overlapping periods. (i.e. 1 (1/7 - 1/12), 1 (1/10 - 1/20) )
I'm going to go with SQL-Server syntax because it's what I'm most comfortable with, but these operations should be something you could do in most sql environments with a little modification. (I'm using a temp table and CTE's, but you could use sub-queries)
create table dbo.[Status] (
[status] int,
[start] date,
[end] date
)
insert into dbo.[Status] ([status], [start], [end])
values
(32, '20170101', '20170201'),
(32, '20170201', '20170204'),
(1, '20170204', '20170306'),
(1, '20170306', '20170509'),
(32, '20170509', '20170519'),
(32, '20170519', '20170622')
create table dbo.Result (
PeriodID int identity, -- to make grouping and self-referential joins easier
Status int,
start date,
next_start date null,
[end] date null
)
select * from dbo.[Status]
-- This will get you all the periods and their start dates
;with cteExcludeTheseRows(status, start) as (
-- These are the records where the Start date matches an end date for the same status group. As a result these aren't real periods, just extensions.
select S.status, S.start
from [Status] S
join [Status] Prior on S.Status = Prior.status and S.start = Prior.[end]
)
insert into dbo.Result (status, start)
select
S.status,
S.start
from [Status] S
left join cteExcludetheserows Exclude on S.status = Exclude.status and S.start = Exclude.start
where Exclude.status is null
-- Reference the temp table to get the next start period for your status groups, that way you know that the end date for that period has to be less then that date
;with cteNextStart (PeriodID, next_start) as (
select
R.PeriodID,
next_start = min(next.start)
from dbo.Result R
join dbo.Result next on R.status = next.status and r.start < next.start
group by R.PeriodID
)
update R
set R.next_start = next.next_start
from dbo.Result R
join cteNextStart next on R.PeriodID = next.PeriodID
-- Now get the end date for each period by looking back at your main status table
;with cteEnd (PeriodID, [end]) as (
select
R.PeriodID,
[end] = max(s.[end])
from dbo.Result R
join [Status] S on R.status = s.status and S.[end] between R.start and isnull(R.next_start, '99991231')
group by R.PeriodID
)
update R
set R.[end] = [end].[end]
from dbo.Result R
join cteEnd [end] on R.PeriodID = [end].PeriodID
-- And finally, here you have your result set
select
status,
start,
[end]
from dbo.Result
order by start, status
drop table dbo.[Status]
drop table dbo.Result
|
[
"stackoverflow",
"0050041952.txt"
] |
Q:
XML XSD Regex for xsd:NMTOKEN
I am struggling to come up with a regex that will handle the NMTOKEN definition;
The type xsd:NMTOKEN represents a single string token. xsd:NMTOKEN
values may consist of letters, digits, periods (.), hyphens (-),
underscores (_), and colons (:). They may start with any of these
characters. xsd:NMTOKEN has a whiteSpace facet value of collapse, so
any leading or trailing whitespace will be removed. However, no
whitespace may appear within the value itself.
I am new to Regex and not sure of a good place to start with the criteria on this regex
Here is the example i was working off; \^[a-zA-Z0-9._\-:]*$\g
A:
Turns out i was really close but because of the way the pattern was being compiled, i needed to escape the escape (because it's received in a string format)
So i went from;
pattern: "^[a-zA-Z0-9._\-:]*$"
to...
pattern: "^[a-zA-Z0-9._\\-:]*$"
I wouldn't have had this issue if i was writing the regex directly in it's use, but because it was being rendered from a JSON feed, as a string, it needed escaping (twice)
|
[
"stackoverflow",
"0035976499.txt"
] |
Q:
Avoiding blank values in form when updating a model with Nested Attributes
I have an app where Users can choose their favorite colors.
The models are as shown below. Essentially the model UserColor is a simple mapping between a User and a Color
class User < ActiveRecord::Base
has_many :colors, dependent: :destroy
accepts_nested_attributes_for :colors, allow_destroy: true
end
class UserColor < ActiveRecord::base
belongs_to :user
belongs_to :color
end
class Color < ActiveRecord::Base
end
I have a simple form that lets users choose up to 3 colors from 3 drop down forms (assume repetition of colors is ok). The form is submitted and updated with nested attributes, and essentially just creates (up to) 3 UserColor records.
I filter the params for update in my controller as follows:
params.require(:user).permit(
colors_attributes: [
:id,
:color_id,
:_destroy
]
)
How to avoid blanks?
If the user only selects 1 color, the 2nd and 3rd drop downs are still blank. The nested hash gets submitted as below (no "id" attributes because it's a new record at this point, but otherwise it would have one)
{
"colors_attributes"=> {
"0"=>{"color_id"=>"17", "_destroy"=>""},
"1"=>{"color_id"=>"", "_destroy"=>""},
"2"=>{"color_id"=>"", "_destroy"=>""}
}
}
This is unacceptable because the last two records have blank color_id values, which violates a non-null criteria on that field and fails my model save validation.
Is there a good way to filter out or avoid blanks here? I can obviously hack around it by looping through and removing blanks, but is there a more "rails way" accepted way to handle this?
A:
Use the :reject_if option.
From http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html (with your models):
accepts_nested_attributes_for :colors, reject_if: proc do |attributes|
attributes['color_id'].blank?
end
|
[
"stackoverflow",
"0006271418.txt"
] |
Q:
Iterating over a collection with an Activity for interacting with the properties of the objects
How would I iterate over a collection with a different Activity to interact with each object within the collection?
For example if I have a survey collection (List maybe) full of question groups and questions, how would I have an Activity/layout for each question group and question given the fact that the questions within the collections are dynamically loaded?
A:
You can use Activity.startActivityForResult(..) to start up the Intent and specify that you expect it to return something. To exit the Intents, just call finish().
|
[
"stackoverflow",
"0015481651.txt"
] |
Q:
Listview java.lang.NullPointerException
When clicking on my list view item, the next activity will not launch and I receive a NullPointerException error. logcat points to Line 130( I think) but I m not sure what changes to make. This worked fine until I implemented a cursor loader with content provider.
logcat:
03-18 09:52:20.737: E/AndroidRuntime(1143): FATAL EXCEPTION: main
03-18 09:52:20.737: E/AndroidRuntime(1143): java.lang.NullPointerException
03-18 09:52:20.737: E/AndroidRuntime(1143): at com.loginplus.home.LoginList.onItemClick(LoginList.java:130)
03-18 09:52:20.737: E/AndroidRuntime(1143): at android.widget.AdapterView.performItemClick(AdapterView.java:292)
03-18 09:52:20.737: E/AndroidRuntime(1143): at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
03-18 09:52:20.737: E/AndroidRuntime(1143): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
03-18 09:52:20.737: E/AndroidRuntime(1143): at android.widget.AbsListView$1.run(AbsListView.java:3168)
03-18 09:52:20.737: E/AndroidRuntime(1143): at android.os.Handler.handleCallback(Handler.java:605)
03-18 09:52:20.737: E/AndroidRuntime(1143): at android.os.Handler.dispatchMessage(Handler.java:92)
03-18 09:52:20.737: E/AndroidRuntime(1143): at android.os.Looper.loop(Looper.java:137)
03-18 09:52:20.737: E/AndroidRuntime(1143): at android.app.ActivityThread.main(ActivityThread.java:4424)
03-18 09:52:20.737: E/AndroidRuntime(1143): at java.lang.reflect.Method.invokeNative(Native Method)
03-18 09:52:20.737: E/AndroidRuntime(1143): at java.lang.reflect.Method.invoke(Method.java:511)
03-18 09:52:20.737: E/AndroidRuntime(1143): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-18 09:52:20.737: E/AndroidRuntime(1143): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-18 09:52:20.737: E/AndroidRuntime(1143): at dalvik.system.NativeStart.main(Native Method)
ListView:
39. public void onCreate(Bundle savedInstanceState) {
40. super.onCreate(savedInstanceState);
41.
42. setContentView(R.layout.login_listview);
43. getSupportLoaderManager().initLoader(LOADER_ID, null, this);
44.
45. String[] from = { BaseColumns._ID, dataStore.COLUMN_NAME_SITE};
46. int[] to = {R.id.rusName};
47.
48. adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, from, to);
49.
50.
51. loginList = (ListView)
52. findViewById(R.id.loginlist);
53. loginList.setOnItemClickListener(this);
54.
55. webLogin = (Button)
56. findViewById(R.id.button3);
57. webLogin.setOnClickListener(this);
58. }
59.
60. public Loader<Cursor> onCreateLoader(int id, Bundle args) {
61.
62. String[] projection = { BaseColumns._ID, dataStore.COLUMN_NAME_SITE};
63. CursorLoader cursorloader = new CursorLoader(this, ListProvider.CONTENT_URI, projection, null , null, null);
64. return cursorloader;
65. }
66.
67. public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
68. adapter.changeCursor(cursor);
69. }
70. public void onLoaderReset(Loader<Cursor> cursorLoader) {
71. adapter.changeCursor(null);
72. }
73.
74.
75. @Override
76. public void onClick (View v) {
77. Intent webLoginIntent = new Intent (this, LoginPlusActivity.class);
78. startActivity(webLoginIntent);
79. }
80.
81. public List<String> populateList (){
82.
83. List<String> webNameList = new ArrayList<String>();
84.
85. dataStore openHelperClass = new dataStore (this);
86.
87. SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
88.
89. Cursor cursor = sqliteDatabase.query(dataStore.TABLE_NAME_INFOTABLE, null, null, null, null, null, dataStore.COLUMN_NAME_SITE, null);
90.
91. while (cursor.moveToNext()){
92. String sName = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_SITE));
93. String wUrl = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_ADDRESS));
94. String uName = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_USERNAME));
95. String pWord = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_PASSWORD));
96. String lNotes = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_NOTES));
97.
98. LoginDetails lpDetails = new LoginDetails();
99. lpDetails.setsName(sName);
100. lpDetails.setwUrl(wUrl);
101. lpDetails.setuName(uName);
102. lpDetails.setpWord(pWord);
103. lpDetails.setlNotes(lNotes);
104.
105. loginArrayList.add(lpDetails);
106. webNameList.add(sName);
107. }
108.
109. cursor.close();
110. return webNameList;
111. }
112.
113.
114.
115. @Override
116. protected void onResume() {
117. super.onResume();
118.
119.
120. adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, new String[] { dataStore.COLUMN_NAME_SITE}, new int[]{R.id.loginlist});
121. loginList.setAdapter(adapter);
122. }
123.
124. @Override
125. public void onItemClick(AdapterView<?> arg0 , View arg1, int arg2, long arg3) {
126. Toast.makeText(getApplicationContext(), "Selected ID :" + arg2, Toast.LENGTH_SHORT).show();
127.
128. Intent updateDeleteLoginInfo = new Intent (this, UpdateDeleteLoginList.class);
129.
130. LoginDetails clickedObject = loginArrayList.get(arg2);
131.
132. Bundle loginBundle = new Bundle();
133. loginBundle.putString("clickedWebSite",clickedObject.getsName());
134. loginBundle.putString("clickedWebAddress",clickedObject.getwUrl());
135. loginBundle.putString("clickedUserName",clickedObject.getuName());
136. loginBundle.putString("clickedPassWord",clickedObject.getpWord());
137. loginBundle.putString("clickedNotes",clickedObject.getlNotes());
138.
139. updateDeleteLoginInfo.putExtras(loginBundle);
140.
141. startActivityForResult(updateDeleteLoginInfo, 0);
142. }
143. }
A:
This is because loginArrayList is null. You should initialize or fill it before using it.
|
[
"stackoverflow",
"0049345082.txt"
] |
Q:
TcpListener and NetworkStream doesn't get data
I am trying to receive a message from an equipment. This equipment is an authentication terminal, and it will send the message as soon as the user set his credentials.
Also, the manual of the equipment says the message will be sent in the ILV format, standing I for identification, L for length and V for value.
a normal message would be:
I -> 0x00 (byte 0 indicating success)
L -> 0x04 0x00 (two bytes for length, being 4 the length in this case)
V -> 0x35 0x32 0x38 0x36 (the message itself)
The message is sent in TCP protocol, so I created a socket using the TcpListener class, following this sample from Microsoft:
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v=vs.110).aspx
new Thread(() =>
{
TcpListener server = null;
try
{
Int32 port = 11020;
IPAddress localAddr = IPAddress.Parse("192.168.2.2");
server = new TcpListener(localAddr, port);
server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
server.Start();
byte[] bytes = new byte[256];
String data = null;
while (true)
{
TcpClient client = server.AcceptTcpClient();
data = null;
NetworkStream stream = client.GetStream();
int i = 0;
while((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// this code is never reached as the stream.Read above runs for a while and receive nothing
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
}
client.Close();
}
}
catch (SocketException ex)
{
// Actions for exceptions.
}
finally
{
server.Stop();
}
}).Start();
If the stream.Read is removed, then the code flows (although I got nothing either), however if I put any stream.Read statement the execution holds for a while like it was waiting for some response, and then it ends with no response, all bytes read is zero.
I am running Wireshark on the computer and the data is being sent.
Anybody knows what I am doing wrong?
A:
I think the problem is right in the Read method, which halts until the buffer fills completely, but that's obviously won't happen anytime.
In that while-loop, you should spin by checking for available data first, then read them and append to the byte-array. Moreover, since the loop become too "tight", it's better to yield the control to the task scheduler for a bit.
Here is an example:
while (true)
{
if (stream.DataAvailable)
{
int count = stream.Read(bytes, i, bytes.Length);
i += count;
// ...add something to detect the end of message
}
else
{
Thread.Sleep(0);
}
}
It's worthwhile to notice that there's no timeout, but that's a very common feature in order to quit the loop when no data (or broken) are incoming.
Furthermore, the above pattern is not the best way to accumulate data, because you may get an exception when too many bytes are received. Consider a spurious stream of 300 bytes: that will overflow the available buffer. Either use the "bytes" as a temporary buffer for what the Read method gives, or provide a safety check before calling the Read method (so that you may provide the best byte count to read).
Useful links here:
https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream.read?view=netframework-4.7.1#System_Net_Sockets_NetworkStream_Read_System_Byte___System_Int32_System_Int32_
|
[
"stackoverflow",
"0012342313.txt"
] |
Q:
Call TObject.GetInterface free object
I'm trying of execute a code like this:
IFoo = Interface
procedure DoFoo;
end;
TFoo = class (TInterfaceObject, IFoo)
.....
procedure DoFoo;
end;
TFoo2 = class (TInterfaceObject)
......
end;
TGenClass = class
class function DoSomething<T: class, cronstructor>: T;
end;
class function TGenClass.DoSomething<T>: T;
var Obj: T;
Foo: IFoo;
begin
Obj := T.Cretae;
if Obj.GetInterfaceEntry(IFoo) <> nil then
begin
Obj.GetInterface(IFoo, Foo);
Foo.DoFoo;
end;
result := Obj;
end;
......
var f: TFoo;
f2: TFoo2;
begin
f:= TGenClass.DoSomeThing<TFoo>;
f2:= TGenClass.DoSomeThing<TFoo2>;
f2.free;
f.free;
end;
When I execute this code, f.free raise a exception, because is already free, I suppose, because if I comment this lines
Obj.GetInterface(IFoo, Foo);
Foo.DoFoo;
it work.
¿How can execute IFoo interface without free object?
thk.
ADD:
Thanks all. I understand.
I tried to return IFoo with same result. My problem is that T could not be TInterfacedObject. The Java code I trying to convert is:
public void dataIterate(int recNo, ResultSet data) throws SQLException {
try {
Constructor c = itemClass.getDeclaredConstructor();
c.setAccessible(true);
Object item = c.newInstance();
if (item instanceof CustomInitialize) ((CustomInitialize)item).initialize(data);
else {
if (metadata == null ) metadata = data.getMetaData();
for (int i=1; i<= metadata.getColumnCount(); i++)
assignProperty(itemClass, item, "set"+metadata.getColumnName(i).toLowerCase(), data.getObject(i));
}
add((E)item);
} catch (Exception ex) {
throw new SQLDataException(ex);
}
..........
Delphi example code:
program Project4;
{$APPTYPE CONSOLE}
{$R*.res}
uses
System.SysUtils, System.Rtti;
type
IFoo = Interface
['{F2D87AE6-1956-4B82-A28F-DC011C529849}']
procedure DoFoo;
end;
TFoo = class (TInterfacedObject, IFoo)
private
FName: String;
public
procedure DoFoo;
property Name: String Read FName write FName;
end;
TFoo2 = class (TObject)
private
FName: String;
published
property Name: String Read FName write FName;
end;
TGenClass = class
class function DoSomething<T: class, constructor>: T;
end;
class function TGenClass.DoSomething<T>: T;
var Obj: T;
Foo: IFoo;
Ap: TRttiProperty;
Ctx: TRttiContext;
begin
Obj := T.Create;
if Obj.GetInterfaceEntry(IFoo) <> nil then
begin
Obj.GetInterface(IFoo, Foo);
Foo.DoFoo;
end;
Ctx.GetType(TypeInfo(T)).GetProperty('Name').SetValue(TObject(Obj),'AName');
result := Obj;
end;
{ TFoo }
procedure TFoo.DoFoo;
begin
writeln('Foo executed.');
end;
var f: TFoo;
f2:TFoo2;
begin
try
f:= TGenClass.DoSomeThing<TFoo>;
f2:= TGenClass.DoSomeThing<TFoo2>;
writeln(f2.Name);
writeln(f.Name); //<-- raise exception
f.free;
f2.Free;
readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
A:
Let's take a look at this code:
class function TGenClass.DoSomething<T>: T;
var Obj: T;
Foo: IFoo;
begin
Obj := T.Create;
if Obj.GetInterfaceEntry(IFoo) <> nil then
begin
Obj.GetInterface(IFoo, Foo);
Foo.DoFoo;
end;
result := Obj;
end;
After Obj := T.Create, the object has a reference count of zero, because no interface variable has yet referenced it. Then you call GetInterface and take an interface reference in Foo. So the object now has a reference count of 1. Then the function returns and Foo goes out of scope. This reduces the reference count to 0 and so the object is freed.
When you use TInterfacedObject, you must always hold an interface variable. So that the reference counting can manage the object's life. In this case you have mixed object references and interface variables and that invariably leads to pain and anguish.
I can't really advise you on what your code should look like because I don't know what your problem is. All I have attempted to do is to explain the behaviour for you. Perhaps DoSomething should be returning IFoo rather than T. Or perhaps you need to stop using reference counted lifetime management. Very hard to be sure from here.
|
[
"stackoverflow",
"0017271316.txt"
] |
Q:
Order By month and year in sql with sum
I have a stored procedure and the select statement is:
SELECT { fn MONTHNAME(OrderDate) } AS MonthName, YEAR(OrderDate) AS Year, SUM(TotalValue) AS Profits
FROM [Order]
WHERE (YEAR(OrderDate) = @year)
GROUP BY { fn MONTHNAME(OrderDate) }, YEAR(OrderDate)
this shows the sum total for every month
But I need to order the result by month and year coz my result shown like:
April 2013
February 2013
January 2013
June 2013
March 2013
May 2013
What is the solution in such a case?
A:
Try this:
SELECT { fn MONTHNAME(OrderDate) } AS MonthName, YEAR(OrderDate) AS Year, SUM(TotalValue) AS Profits
FROM [Order]
WHERE (YEAR(OrderDate) = @year)
GROUP BY { fn MONTHNAME(OrderDate) }, MONTH(OrderDate), YEAR(OrderDate)
order by Year(orderDate),month(OrderDate)
Note you need to add any fields you are ordering by to the group by clause
|
[
"stackoverflow",
"0046548425.txt"
] |
Q:
Need specific cron job explained that uses flock -n + .lock file + /bin/bash
I have this cronjob, that is not working for some reason, but I don't entirely understand what it does, could someone explain?
flock -n /var/www/vhosts/blia.preview.be/scripts/blia_bab_import.sh.lock /bin/bash /var/www/vhosts/blia.preview.be/scripts/blia_bab_import.sh
I googled that flock is supposed to lock the file and only run if it can lock the file, so that the job cannot run multiple times at the same time.
What does the -n do?
flock -n
Why is this a .lock file?
/var/www/vhosts/blia.preview.be/scripts/blia_bab_import.sh.lock
I have no idea what the /bin/bash is supposed to do?
/bin/bash
Is this the script I want to execute?
Why is it added as a .lock first?
/var/www/vhosts/blia.preview.be/scripts/blia_bab_import.sh
A:
flock -n LOCK-FILE COMMAND
In your case:
-n: if flock cannot obtain the LOCK-FILE, i.e. it already exists, it will stop right there, and not execute the COMMAND.
So the -n ensures only one instance of COMMAND can run at a time.
in your case LOCK-FILE is /var/www/vhosts/blia.preview.be/scripts/blia_bab_import.sh.lock
The LOCK-FILE is what you decide it to be. flock will check for that file as a lock. It could be named anything, anywhere on your system, but doing it this way is nice since you know what the .lock file is used for.
To illustrate, you could do flock -n /tmp/some_lock_file.txt script.sh. The value is not enforced, you decide what you want to use.
COMMAND in your case is /bin/bash /var/www/vhosts/blia.preview.be/scripts/blia_bab_import.sh
The script you want to execute is the value of COMMAND, so again for you: /bin/bash /var/www/vhosts/blia.preview.be/scripts/blia_bab_import.sh
/bin/bash is to specify that the script blia_bab_import.sh must run inside a bash shell. You could do without by using the #!/bin/bash first line in your .sh file.
|
[
"stackoverflow",
"0037650496.txt"
] |
Q:
How to create directory based on the username
I want to create a directory based on the username(user) that is logged in, to upload images to that folder, so when each user uploads an image file it will be sent to the directory based on the username and the image file is saved in that folder
$_SESSION["user"];
I use session to get the username, now I want to create a folder inside a folder name uploads
mkdir('/uploads/' . $_SESSION['user']);
and make $target_dir= location for upload as above one.
A:
Use of mkdir() and its parameter:
recursive Allows the creation of nested directories specified in the pathname. Defaults to FALSE.It means
Path : path of directory including directory name.
Permission : 0777
Recursive Flag : when you need to create subfolder.
$path = '/upload/UserA';
mkdir($path, 0777, true);
Note
/upload/ is almost certainly wrong. It points to the "upload" directory in the root directory, where you most likely don't have the permission to create one.
|
[
"softwareengineering.stackexchange",
"0000233379.txt"
] |
Q:
Developing a virtual machine / sandbox
I'm interested in learning how a virtual machine/sandbox actually works. I have developed an 8051 emulator and also wrote a dissassembler for x86, so this part of a virtual machine is not really the problem.
What I'm interested in, is the sandbox functionality of it. To illustrate what I mean consider this example.
Let's assume I have a function which simply opens a file. So nothing fancy.
int fd = open(path);
Now when this code is executed natively it will go to the operating system and opens the file (assuming that it exists). Now when I run this in a virtual machine environment, the specified path is not the one that the operating system sees, but rather something that the VM will substitute, thus redirecting the open call.
So what I'm interested in is, how a VM can do this, when the executed code is run natively (like x86 on a x86) because for an interpreted VM it is rather obvious.
When I google for virtual machines I either find only links talking about interpreters like Java, LLVM or similar, but nothing that goes into more detail. I downloaded the sourcecode from Oracle Virtual Box, but as this is a rather big codebase, it's quite hard to understand the concept just form digging in that code.
A:
Now when I run this in a virtual machine environment, the specified path is not the one that the operating system sees, but rather something that the VM will substitute
This is not true for the vast majority of VMs (VMWare, VirtualBox, QEmu, Parallels, VirtualPC, …) These are all hardware virtualizers, they don't virtualize the OS. So, the open call will simply go to the OS inside the VM, which (typically) doesn't even know that it is running inside a VM. (There are performance advantages if the OS knows that it is running inside of a VM and talks to the VM instead of talking to the virtualized or emulated hardware, but that is technically no longer virtualization, it is paravirtualization.)
Of course, this just pushes the question one layer down: when the OS kernel wants to write to some specific block on the hard disk, how does that work? Well, in the worst case, the VM has to intercept the BIOS calls and map the block numbers to some file on the host system's hard disk. But this is where paravirtualization comes in: no modern OS uses the BIOS anymore, they use specialized drivers. And you could then simply provide a "virtual" driver that knows how to talk to the VM directly.
You still need to map the block numbers, of course. The simplest solution is to create a file in the host system that is the same size as the emulated hard disk. However, since hard disks tend to be mostly empty, this would be a waste of space, so most VMs employ a lazy scheme where the file only grows when needed. They might also use compression.
What you are talking about is more like OS virtualization (aka containers) than hardware virtualization. But really, it works the same way: instead of virtualizing the x86 instruction set, it virtualizes the "Linux Kernel ABI Instruction Set". IOW: it simply treats the Linux Kernel as an interpreter for a certain language (the syscalls) and then puts another interpreter on top. That's how OpenVZ works on Linux, for example, or Solaris Zones, or DLPAR on the IBM PowerSeries.
|
[
"stackoverflow",
"0009757243.txt"
] |
Q:
Resource Id Mismatch in Android Development
I have created a menu for my activity by writing layout and inflating it in my activity.
When i written onOptionItemSelected The Rid recieved from the event listener and that i have from R.id.menu are different eventhough i clicked on the correct menu item. It is one digit lesser than actual. so my click function is not working?
A:
They are 2 different ID.
The id that you use to inflate the menu is R.menu.*
But the id that you use to uniquely identify your menu is R.id.*
See here for sample:
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/MenuInflateFromXml.html
|
[
"stackoverflow",
"0001886792.txt"
] |
Q:
Javascript syntax error... How can I find out more information?
Apologies if this is a stupid question as Im completly new to JAvascript and web programming!
I'm currently using Dreamweaver to do some test scripts and the internal JS editor is highlighting a syntax error with my script. The only problem is that there is no indication as to what the error is or what I might need to do to fix it!
When I paste this code directly into the web page, the script seems to work without issue!
My script is as follows (saved in an external .js file):
1 // JavaScript Document
2 <script type="text/javascript">
3
4 function coloralternatetablerows(id)
5 {
6 // If the tag exists within the document
7 if(document.getElementsByTagName)
8 {
9 // rest of the script ommitted for clarity
10 }
11 }
The synax error is highlighted as line 7.
Can anyone help me figure this out?!
More importantly... can anyone direct me to a good resource to help me with this sort of issue in the future?
A:
Your Javascript code is in a seperate .js file so you don't need the <script> tag in there.
Get rid of the <script> tag completely.
In your HTML page you'll be loading in your external .js file using
<script type="text/javascript" src="myscript.js"></script> but the .js file its self should have no HTML in it (like the <script> tag)
|
[
"stackoverflow",
"0027994803.txt"
] |
Q:
Highlight tabbed-to element (using jQuery/CSS/anything)
I am trying to test the tabbing on a page but I cannot SEE what I've just tabbed to.
I managed to highlight the input element types text and textarea pretty easily. Radio did not work, but affecting the parent element did work. Here's my jquery:
$(":input").focusin( function() {
if($(this).attr('type') === 'radio') {
$(this).parent().attr('style', 'background-color: yellow !important');
} else {
$(this).attr('style', 'background-color: yellow !important');
}
});
$(":input").focusout( function() {
if($(this).attr('type') === 'radio') {
$(this).parent().css('background-color','');
} else {
$(this).css('background-color','');
}
});
But now I still have some other elements that I'm tabbing to and I cannot even tell what they are. All I know is it takes several tab presses to get from the last radio group to the next "select" element (which I can see is focused even without extra jquery code). After that is a button, which I also would like to be highlighted.
Do I have to list conditions for every single element? Or use a selector like $(":input,:button,[etc]")? Is there some easy way I can just have the element, whatever it is, highlighted after it is tabbed to?
A:
You can use the :focus pseudo-class in CSS. It is well supported except IE 7 and older; if you need to support them, use a polyfill like Selectivzr. However, note that :focus matches the focused element, no matter how it reached focus (e.g. via tabbing, via a click, or an invocation of the focus() method).
Example:
<style>
:focus { outline: solid red }
</style>
<p><input placeholder="Click me, then tab">
<p><input type=radio>
<p><a href="https://developer.mozilla.org">link</a>
<p contenteditable=true>This is editable and focusable
|
[
"math.stackexchange",
"0003251385.txt"
] |
Q:
Is any subset of the naturals a semi-linear set?
A subset $X$ of $\mathbb{N}^n$ is linear if it is in the form:
$u_0 + \langle u_1,...,u_m \rangle = \{ u_0 + t_1 u_1 + ... + t_m u_m \mid t_1,...,t_n \in \mathbb{N}\}$ for some $u_0,...,u_m \in \mathbb{N}^n$
$X$ is semilinear if it is the union of finitely many linear subsets. So my question is: Is any subset of the natural numbers a semi-linear set, i.e., can we express any subset of the natural numbers as the finite union of linear sets?
A:
Consider the set $\{2^n:n\in\mathbb{N}\}$, i.e., the powers of $2$. Note that the inter-element differences are all different. Therefore, the only linear subsets are singleton elements. Hence, this is not a finite union of linear sets.
|
[
"stackoverflow",
"0055321253.txt"
] |
Q:
React - map array to child component
I'm coding a site with multiple pages. A page ComponentA, have a child component that return sections with titles and paragraphs.
The array in ComponentA pass data as props to the child. Inside the child, a map function return the paragraphs correct. What's missing for the titles, how would you do to pass title1 to paragraph1, title2 to paragraph2 and so on?
ComponentA:
import Child from "../components/child";
const ComponentA = () => {
<Layout>
<h1>Home Page</h1>
<Child title={info.title} text={info.text} />
</Layout>
}
const info = {
title: ["Title1", "Title2"],
text: ["Paragraph1", "Paragraph2"]
};
Child component:
const Child = ({ text, title }) => {
return (
<div>
{text.map(text => {
return (
<div>
<h3>{title}</h3>
<p>{text}</p>
</div>
);
})}
</div>
);
};
A:
Your info object is not an iterable list - so I would convert them into a list {title, text} like so:
const data = info.title.map((e,i) => {
return {title : e, text: info.text[i]}
})
Now I would shift the map() function to ComponentA instead of Child as that makes the child component more meaningful.
See demo below:
const info = {
title: ["Title1", "Title2"],
text: ["Paragraph1", "Paragraph2"]
};
const data = info.title.map((e,i) => {
return {title : e, text: info.text[i]}
})
const ComponentA = () => {
return (
<div>
<h1>Home Page</h1>
{ data.map(item => {
return (
<Child key={item.title} title={item.title} text={item.text} />
);
})
}
</div>
)
}
const Child = ({ text, title }) => {
return (
<div>
<h3>{title}</h3>
<p>{text}</p>
</div>
);
};
ReactDOM.render(
<ComponentA/>,
document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
|
[
"stackoverflow",
"0026333961.txt"
] |
Q:
Difference between Get-Unique and select-object -unique
Using PowerShell, I import csv-data from file via "import-csv" into the object $csvList. This csv-data has a column called Benutzer. When doing something like this:
$csvList | %{$_.Benutzer} | select-object -unique
there is nothing special: as expected, the unique entries in Benutzer are returned, which are around 10 items. However,
$csvList | %{$_.Benutzer} | get-unique -asstring
or
$csvList | Group($_.Benutzer)
seem to treat each entry as unqiue, i.e. the entire array of 260 Benutzer is returned in case of get-unique and 260 groups are created in case of the group statement.
I am using PowerShell 4.0.
Any idea what is going on here is appreciated...
A:
From Get-Unique help:
The Get-Unique cmdlet compares each item in a sorted list...
Select-Object -Unique does not require objects to be pre-sorted.
Example:
PS> 9,8,9,8 | Get-Unique -AsString
9
8
9
8
Example:
PS> 9,8,9,8 | Sort-Object -Unique
8
9
As for Group-Object, the syntax of the command should be different, replace ($_.Benutzer) with the property name Benutzer:
$csvList | Group-Object Benutzer
|
[
"stackoverflow",
"0043252074.txt"
] |
Q:
Convert string date to object date for database
How do I convert date "20170101" to Date object so that Doctrine Date Time accept it for the database?
I have tried this;
$date = "20170101";
$date = strtotime($date);
$newDate = date("Y-m-d H:i:s", $date);
$order->setDate($newDate);
But I still get an error;
DateTimeType ->convertToDatabaseValue ('2017-01-01 00:00:00',
object(PostgreSQL92Platform))
Call to a member function format() on string
Current dates that are already in the database are the same format
A:
this should work
$date = \DateTime::createFromFormat('Ymd', '20170101');
|
[
"stackoverflow",
"0033148095.txt"
] |
Q:
Is it possible to make an md-button smaller?
I want my buttons showing left- and right arrow and NOW text to be as small as possible. How do I do that?
<div ng-controller="DateCtrl" layout="row" flex>
<md-datepicker ng-model="activeDate" md-placeholder="Enter date" ng-change="changeDate()"></md-datepicker>
<div>
<md-button class="md-raised" ng-click="prev()"><</md-button>
<md-button class="md-raised" ng-click="changeToday()">NOW</md-button>
<md-button class="md-raised" ng-click="next()">></md-button>
</div>
</div>
With the current solution the buttons will be arranged as if they were in a layout="column", that is vertically.
Before I dig into this CSS-style, I just wanted to check if there is a preferred Angular-Material way of doing this?
A:
Add the following to your styles:
.md-button {
min-width: 1%;
}
Alternatively, use a custom class:
.md-button.md-small {
min-width: 1%;
}
Or, in Angular Material 2:
.mat-button.mat-small {
min-width: 1%;
}
A:
Try the following class in your styles. You can adjust the pixel depending on how big/small you want the button to be.
.md-button.md-small {
width: 20px;
height: 20px;
line-height: 20px;
min-height: 20px;
vertical-align: top;
font-size: 10px;
padding: 0 0;
margin: 0;
}
A:
You could use css transform: scale(). You have to play with margins a little bit, but it isn't much code and you can go smaller or bigger pretty easily.
.shrink-2x {
transform: scale(0.5);
}
.enlarge-2x {
transform: scale(1.5);
}
Example
|
[
"stackoverflow",
"0025865083.txt"
] |
Q:
selecting dropdown list and change step attribute of input
i want when choosed A option , input value will be 10,20,30 ...
for B option, input value 5,10,15,20
that code didnt work what is wrong
<select onchange="changeValue(this);" id="size" name="attribute_size">
<option selected="selected" value="">choose option…</option>
<option class="active" value="A">A</option>
<option class="active" value="B">B</option>
</select>
<input min="1" step="1" id="quantity" value="1" title="quantity" class="input-text qty text" size="4" type="number">
function changeValue() {
var option2 = document.getElementById('size').options[document.getElementById('size').selectedIndex].id;
if (option2 == "A") {
document.getElementById('quantity').setAttribute('step', "10");
}
else (option2 == "B")
{
document.getElementById('quantity').setAttribute('step', "5");
}
}
A:
You have a missed if after else which was causing console error,
else if (option2 == "B")
Change the min attribute to '0',
<input min="0" step="1" id="quantity" value="0" title="quantity" class="input-text qty text" size="4" type="number">
And Javascript,
function changeValue(that) {
var option2 =that.options[that.selectedIndex].text;
var inputElm = document.getElementById('quantity');
inputElm.value = 0;
if (option2 == 'A') {
inputElm.setAttribute('step', '10');
} else if (option2 == 'B') {
inputElm.setAttribute('step', '5');
}
}
DEMO
Also, you can use the this onject passed in the parameter when operating on the current object.
|
[
"stackoverflow",
"0008788341.txt"
] |
Q:
Orderly execution of multiple rule defined in one DRL file
I defined multiples rules in one DRL file, how to set order, want to execute one after another (top to bottom).
A:
Rules are fired automatically when the conditions are met when the inserted facts(objects) are updated. But if in case you want to run it from top to bottom, you can set a property called salience in the rule. The value it takes is an integer. The rule with the highest salience is executed first.
rule "First name mandatory"
salience 10
when
(Person(firstName=="" || firstName==null))
then
...
end
|
[
"stackoverflow",
"0035677585.txt"
] |
Q:
Excel Export as html fails to show borders in Excel 2016
I am exporting html to an Excel xls file using JavaScript as in following demo: http://js.do/sun21170/84913. I have used Google Chrome to run this demo but it should run in Edge or IE or FireFox also.
The problem is that when I open the exported file in Excel 2016, it shows without any borders even though there is CSS in the exported html to show borders.
Question: Is there a way to show the borders when html file opens in Excel? The same html that opens in Excel, renders with borders in a browser, so the CSS for borders is correct. The demo at http://js.do/sun21170/84913 also shows the html being saved in Excel file.
HTML saved as xls file
<html>
<head>
<style> table, td {border:1px solid black} table {border-collapse:collapse}</style>
</head>
<body>
<table>
<tr>
<td>Product</td>
<td>Customer</td>
</tr>
<tr>
<td>Product1</td>
<td>Customer1</td>
</tr>
<tr>
<td>Product2</td>
<td>Customer2</td>
</tr>
<tr>
<td>Product3</td>
<td>Customer3</td>
</tr>
<tr>
<td>Product4</td>
<td>Customer4</td>
</tr>
</table>
</body>
</html>
A:
I finally found the answer after a lot research. It seems that Excel 2016 does not like a border thickness of 1px; anything greater than 1px like 2px or 3px or 4px works. Why Excel 2016 behaves like this is unclear to me.
A demo showing this is at following URL: http://js.do/sun21170/84961
Also, if the border thickness is specified in any other units like em or pt or mm, then a thickness of 1em or 1mm or 1pt or 1mm or .5mm will work.
Even border thickness using pre-defined values like thin or medium or thick works in Excel 2016.
So, the lesson I have learnt is to never specify border thickness of 1 px when using Excel.
Following CSS are different styles that worked in Excel 2016 to create a border.
Border thickness greater than 1px WORKS
var table = "<html><head><style> table, td {border:2px solid black}
table {border-collapse:collapse}</style></head><body><table><tr>";
Border thickness of 1pt WORKS
var table = "<html><head><style> table, td {border:1pt solid black}
table {border-collapse:collapse}</style></head><body><table><tr>";
Border thickness of 1mm WORKS
var table = "<html><head><style> table, td {border:1mm solid black}
table {border-collapse:collapse}</style></head><body><table><tr>";
Border thickness of 1em WORKS
var table = "<html><head><style> table, td {border:1em solid black}
table {border-collapse:collapse}</style></head><body><table><tr>";
Border thickness of thin WORKS
var table = "<html><head><style> table, td {border:thin solid black}
table {border-collapse:collapse}</style></head><body><table><tr>";
|
[
"stackoverflow",
"0004776033.txt"
] |
Q:
How to change an element in a list in erlang
I have a list which I have used the function lists:nth() on to return the value of an element at a certain index. Does anyone know how I can edit this value?
any help would be great
thanks
Mark.
EDIT: Here is a bit more information.
Say I had a list L which represents a line of a text based grid
L = [H,H,H,H,H].
And I want to access a specified element say for example the third one and change it to E. Then if I was to use the list L again it would be
[H,H,E,H,H]
I hope this makes more sense.
Thank you.
A:
A list is immutable, so you can't "change" an item in a list. If you really want to replace an item at a given position, you should append the list before the element with the (changed) element and the remaining list:
1> L=[1,2,3,4,5].
[1,2,3,4,5]
2> lists:sublist(L,2) ++ [lists:nth(3,L)*100] ++ lists:nthtail(3,L).
[1,2,300,4,5]
EDIT: The scenario is a bit unusual, though... Do you have a specific problem at hand? Perhaps it can be expressed better with e.g. a lists:map?
A:
While using functions from lists may result in code that seems clearer it is less efficient as the list of elements before the element you want to change will be copied twice. It is more efficient to write the function yourself, and as you will probably wrap the code using lists in a function I don't feel it will be less clear.
Instead of the code by @D.Nibon I would write the function as:
%% setnth(Index, List, NewElement) -> List.
setnth(1, [_|Rest], New) -> [New|Rest];
setnth(I, [E|Rest], New) -> [E|setnth(I-1, Rest, New)].
%% Can add following caluse if you want to be kind and allow invalid indexes.
%% I wouldn't!
%% setnth(_, [], New) -> New.
The argument order can be discussed; unfortunately the lists module is no help here as it is inconsistent within the module. While this is not a tail-recursive function I feel that it is clearer. Also the difference in efficiency is small or non-existent so I would go with clarity. For more information about this issue see:
http://www.erlang.org/doc/efficiency_guide/myths.html#tail_recursive
http://www.erlang.org/doc/efficiency_guide/listHandling.html#id64759
For a more versatile function instead of just the new value you could pass a fun which would be called with the old value and return the new value. In a library I would probably have both.
A:
When working with lists a all elements are often of similar datatype or meaning. You seldom see lists like ["John Doe","1970-01-01","London"] but rather #person{name="John Doe",...} or even {"John Doe",...}. To change a value in a record and tuple:
-record(person,{name,born,city}).
f(#person{}=P) -> P#person{city="New City"}. % record
f({_,_,_,}=Tuple) -> erlang:setelement(3,Tuple,"New City"). % tuple
This might not solve anything for your particular problem. To take your own example in comment:
f1([H1,H2,_H3,H4,H5],E) -> [H1,H2,E,H4,H5].
If you give a more specific description of the environment and problem it's easier to under which solution might work the best.
Edit: One (rather bad) solution 1.
replacenth(L,Index,NewValue) ->
{L1,[_|L2]} = lists:split(Index-1,L),
L1++[NewValue|L2].
1> replacenth([1,2,3,4,5],3,foo).
[1,2,foo,4,5]
Or slightly more efficient depending on the length of your lists.
replacenth(Index,Value,List) ->
replacenth(Index-1,Value,List,[],0).
replacenth(ReplaceIndex,Value,[_|List],Acc,ReplaceIndex) ->
lists:reverse(Acc)++[Value|List];
replacenth(ReplaceIndex,Value,[V|List],Acc,Index) ->
replacenth(ReplaceIndex,Value,List,[V|Acc],Index+1).
Even better is my function f1 above but maybe, just maybe the problem is still located as discussed above or here.
|
[
"math.stackexchange",
"0002599858.txt"
] |
Q:
Approximation using first order term
I'm trying to understand some equations concerning isentropic nozzle flow, found here (under "flow analysis"):
https://en.wikipedia.org/wiki/Isentropic_nozzle_flow
We have this continuity equation:
$$\rho AV = (\rho+d\rho)(A+dA)(V+dV)$$
Then the next step is:
If only the first-order terms in a differential quantity are retained, continuity takes the form
$$ \frac{dV}{V}+\frac{dA}{A}+\frac{d\rho}{\rho} = 0 $$
I don't understand how this step was made. I understand the concept of approximating a function with Taylor series and neglecting higher order terms when working in small intervals, but I'm still having hard time following how the step was made. Could somebody help me and explain this in more detail? Thank you!
A:
The way one usually goes about showing this is by imagining $dV$, $dA$, and $d\rho$ are themselves first-order small quantities. Then expand:
$$\begin{align} \rho AV &= (\rho + d\rho)(A + dA)(V+dV) \\&= \rho A V + \rho A dV + \rho V dA + AVd\rho + \rho dA dV + A d\rho dV + V d\rho dA + d\rho dA dV
\end{align}$$
Now the terms $dV dA$ or any other term with at least two first-order small quantities multiplied together is a second-order small quantity (or higher-order) and can be assumed to be zero if the first-order small quantity is small. So we have:
$$ \rho AV = \rho A V + \rho A dV + \rho V dA + AVd\rho $$
Divide both sides by $\rho AV$:
$$ 1 = 1 + \frac{dV}{V} + \frac{dA}{A} + \frac{d\rho}{\rho}$$
And finally subtract $1$ from both sides:
$$ 0 = \frac{dV}{V} + \frac{dA}{A} + \frac{d\rho}{\rho}$$
This presentation is a bit informal, but it gets the point across.
|
[
"stackoverflow",
"0007228678.txt"
] |
Q:
How to capture data coming from an AJAX enabled web site?
Some time ago I created an application to dynamically capture data from an asp site navigating it, parsing the html pages I got and storing the selected data into a database.
Now I need to do the same again but this time the web site is developed using AJAX and I don't know how to face the problem. Any ideas are welcome.
Thanks.
A:
I'd suggest two ways of solving you problem:
1) if you create a crawler for one particular site with tons of data to retrieve, write these requests manually (using WebRequest class, for example)
2) if you need universal solution, try some GUI testing tools (Selenium, Telerik WebAii etc.) to run browser into site, so JS and AJAX will be executed by browser.
Depends on you.
|
[
"stackoverflow",
"0032304722.txt"
] |
Q:
Java boolean not passing from class
I have many classes in Java. I want that if I click on a Radiobutton on Window (my main GUI), that the boolean value is passed to other classes.
Here are how they are "architected".
Here is my class Window:
class Window{
Oscillo parent;
Graph graph;
boolean b1=true;
boolean b2 = false;
Window(Oscillo parent){
this.parent = parent;
}
}//end class
Here is my class Graph:
class Graph extends JPanel(){
Window parent;
// tried to get my boolean values from Window but nothing worked
private class SG{
SG(Graphics g, int id){
// tried to get my boolean values from Window but nothing worked
...
}//end private class
}//end class
Here is my class Data:
class Data{
private Oscillo parent;
// tried to get my boolean values from Window but nothing worked
Data (Oscillo parent){
// tried to get my boolean values from Window but nothing worked
}
...
}//end class
Here is my class Oscillo
public class Oscillo implements MessageListener{
Data data;
Window window;
// tried to get my boolean values from Window but nothing worked
...
}//end class
I tried several things, super.b1, parent.b1... and so on, but I couldn't get my boolean values passed from one class to the others.
If u could help me to solve my problem, I would be grateful !
Have a nice day !
Tom
A:
You should expose them to other classes using get methods, as such:
class Window{
Oscillo parent;
Graph graph;
boolean b1=true;
boolean b2 = false;
Window(Oscillo parent){
this.parent = parent;
}
// I would urge you to choose better names that are more clear
// for both variables and methods
boolean getB1() { return b1; }
boolean getB2() { return b2; }
}//end class
And then simply use them to read the values, as such:
class Graph extends JPanel(){
Window parent;
private class SG{
SG(Graphics g, int id){
parent.getB1(); //getting b1's value
}//end private class
}//end class
And so on...
When you only have Oscillo object and you want to access b1 or b2 through its' Window object, add another get method for Window and then chain these calls together as such:
public class Oscillo implements MessageListener{
Data data;
Window window;
//get b1 or b2 by window.getB1() and window.getB2() accordingly
Window getWindow() { return window; }
}//end class
class Data{
private Oscillo parent;
Data (Oscillo parent){
// might be worth checking if window is not null,
// depending on your architecture and invariants
parent.getWindow().getB1();
}
...
}//end class
Hope this helps.
|
[
"stackoverflow",
"0035236426.txt"
] |
Q:
Grails 3 Spring Security override login form
I've found a few things from spring documentation that you can override the login controller and form. I just want to override the login form itself while keeping the default controller. I found this:
In the grails security plugin, the login gsp page is located at grails-app/views/login/auth.gsp and the controller at grails-app/controllers/grails/plugin/springsecurity/LoginController.groovy. I don't think the controller can be overwritten by simply creating your own implementation, but you should be able to override the gsp page by placing your own auth.gsp in the same path shown above, in your app.
https://plus.google.com/117486613280979732172/posts/cvqcfAQVWE6
However, this is just not working to override the page and the default page keeps coming up. Has anyone done this with Grails 3 and spring security libraries?
EDIT:
I'm using OAuth2 by using these libraries and setting up my own beans. I think the other way might be to use grails plugins for spring security. Is there a way to override the login page using these libraries?
compile "org.springframework.boot:spring-boot-starter-security"
compile "org.springframework.security.oauth:spring-security-oauth2:2.0.8.RELEASE"
A:
Ok, since I'm not using the grails spring security plugin, I needed to replace the login page by the guidance here:
http://docs.spring.io/spring-security/site/docs/3.2.x/guides/form.html
Essentially, I had to create a LoginController
class LoginController {
def auth() {
}
def error() {
}
Then, I placed the views in the respective paths: views/login/auth, views/login/error
Here is a sample auth.gsp
<html>
<body>
<h1 id="banner">Login to Security Demo</h1>
<form name="f" action="/login/auth"
method="POST">
<table>
<tr>
<td>Username:</td>
<td><input type='text' name='username' /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password'></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"> <input name="reset" type="reset"></td>
</tr>
</table>
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
</form>
</body>
</html>
Then in configuration of the HttpSecurity:
@Override
public void configure(HttpSecurity http) {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage('/login/auth')
.defaultSuccessUrl("/")
.failureUrl("/login/error")
.usernameParameter("username").passwordParameter("password")
.permitAll()
}
It would be nice to use the grails security plugin but I couldn't figure out how to use OAuth2 with it. If anyone has guidance on that, I'd change my accepted answer.
|
[
"stackoverflow",
"0010784699.txt"
] |
Q:
Can I delay a decorator to happen until I call the function?
First I've learned what Python decorators are and how they work. And I'd like it to do something like this:
def age_over_18(go_enjoy_yourself):
def go_home_and_rethink_your_life():
return 'So you should go home and rethink your life.'
return go_enjoy_yourself if age_stored_somewhere > 18 else go_home_and_rethink_your_life
@age_over_18
def some_porn_things():
return '-Beep-'
But I found out that decorators are executed when the function is first read by Python, that means this function will actually do nothing.
I know I can write something like:
def some_porn_things():
if age_stored_somewhere > 18:
...
else:
...
But I just think decorators are graceful and easy to understand, so the question is:
Can I delay a decorator to happen until I call the function?
A:
The trick is just to ensure that the check happens in your inner function, not the outer one. In your case:
def age_over_18(go_enjoy_yourself):
def are_you_over_18():
if age > 18:
return go_enjoy_yourself()
else:
return 'So you should go home and rethink your life.'
return are_you_over_18
|
[
"stackoverflow",
"0006373343.txt"
] |
Q:
Iterate over an infinite sequence in Ruby
I am trying to solve Project Euler problem #12:
The sequence of triangle numbers is generated by adding the natural
numbers. So the 7th triangle number
would be 1 + 2 + 3 + 4 + 5 + 6 + 7 =
28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five
divisors.
What is the value of the first triangle number to have over five
hundred divisors?
Here's the solution that I came up with using Ruby:
triangle_number = 1
(2..9_999_999_999_999_999).each do |i|
triangle_number += i
num_divisors = 2 # 1 and the number divide the number always so we don't iterate over the entire sequence
(2..( i/2 + 1 )).each do |j|
num_divisors += 1 if i % j == 0
end
if num_divisors == 500 then
puts i
break
end
end
I shouldn't be using an arbitrary huge number like 9_999_999_999_999_999. It would be better if we had a Math.INFINITY sequence like some functional languages. How can I generate a lazy infinite sequence in Ruby?
A:
Several answers are close but I don't actually see anyone using infinite ranges. Ruby supports them just fine.
Inf = Float::INFINITY # Ruby 1.9
Inf = 1.0/0 # Ruby before 1.9
(1..Inf).include?(2305843009213693951)
# => true
(1..Inf).step(7).take(3).inject(&:+)
# => 24.0
In your case
(2..Inf).find {|i| ((2..( i/2 + 1 )).select{|j| i % j == 0}.count+2)==42 }
=> 2880
Your brute force method is crude and can, potentially, take a very long time to finish.
A:
In Ruby >= 1.9, you can create an Enumerator object that yields whatever sequence you like. Here's one that yields an infinite sequence of integers:
#!/usr/bin/ruby1.9
sequence = Enumerator.new do |yielder|
number = 0
loop do
number += 1
yielder.yield number
end
end
5.times do
puts sequence.next
end
# => 1
# => 2
# => 3
# => 4
# => 5
Or:
sequence.each do |i|
puts i
break if i >= 5
end
Programming Ruby 1.9 (aka "The Pickaxe Book"), 3rd. ed., p. 83, has an example of an Enumerator for triangular numbers. It should be easy to modify the Enumerator above to generate triangular numbers. I'd do it here, but that would reproduce the example verbatim, probably more than "fair use" allows.
A:
Infinity is defined on Float (Ruby 1.9)
a = Float::INFINITY
puts a #=> Infinity
b = -a
puts a*b #=> -Infinity, just toying
1.upto(a) {|x| break if x >10; puts x}
|
[
"math.stackexchange",
"0000275494.txt"
] |
Q:
How to calculate $\oint_{C}\frac{dz}{z(z-1)(z-2)}$ when $C$ is a circle around the origin with radius $1.5$?
I wish to calculate $\oint_{C}\frac{dz}{z(z-1)(z-2)}$ when $C$ is
a circle around the origin with radius $1.5$.
I guess that I should somehow apply Cauchy's integral formula here,
but $\frac{1}{z},\frac{1}{z-1}$ are not analytical inside of $C$
so I can't define something like $f(z)=\frac{1}{z(z-2)}$ and calculate
$\oint_{C}\frac{f(z)dz}{(z-1)}$ by Cauchy's.
Can someone please help me understand how to calculate this integral
?
I am guessing there is some trick so I can use Cauchy's integral
formula, but I didn't manage to think of any such tricks.
A:
$$ \oint_c \frac{1}{z(z-1)(z-2)} dz = 2\pi i \; \left [ \; \text{Res}\left (f(z), 0\right ) + \text{Res}\left ( f(z), 1 \right ) \; \right ] = 2\pi i(1/2 - 1) = -\pi i $$
Or simply, since pole of $z=2 > 1.5 $
$$ \oint_c \frac{1}{z(z-1)(z-2)} dz = \oint_c \left( \frac{1}{2 (-2+z)}-\frac{1}{-1+z}+\frac{1}{2 z} \right ) dz \\
= \oint_c \frac{1}{2z}dz - \oint_c\frac{1}{z-1} = \pi i - 2 \pi i = -\pi i$$
I hope I am not wrong!!
|
[
"stackoverflow",
"0011546834.txt"
] |
Q:
QGLWidget paintEvent: where to initialize openGL?
It seems that the paintEvent method of the QGLWidget is called before initializeGL, so where am I supposed to put my openGL initialization code?
I'm putting it into the paintEvent method like this:
void MyGLWidget::paintEvent(...)
{
makeCurrent();
..save modelview and projection matrices..
// This is initialization code
GLenum init = glewInit();
if (GLEW_OK != init)
{
/* Problem: glewInit failed, something is seriously wrong. */
qWarning() << glewGetErrorString(init);
}
// Dark blue background
glClearColor(0.2f, 0.0f, 0.5f, 0.0f);
// Enable depth test
glEnable(GL_DEPTH_TEST);
// End initialization code
... drawing code
QPainter painter(this);
...overpainting..
}
I really don't like the idea of having my glew library initialization function called every time a paintEvent is raised... although that's working.
Any suggestion?
A:
You have to initialize OpenGL in initializeGL(), there is no other option.
But you also have to draw inside paintGL, not inside paintEvent, so that is where your mistake is.
|
[
"stackoverflow",
"0049341842.txt"
] |
Q:
HTML Text editor div - force text to start from bottom - bottom to top textbox
In short, i want a textbox bottom to top that keeps the width and height that i defined. Keeping the cursor bottom left works when adding style position:relative, which makes the div automatically grow when text is added. When using position:absolute, the cursor changes to top-left.
How to reproduce the problem:
Open the jsfiddle and write bottom right more text into the textbox until it overflows. The goal is to keep the size of the div but at the same time keep the caret bottom left
I am forced to go with a div "contenteditable=true" in order to create a nice textbox. The div is created by a server "swellrt" and i can add attributes and styles but i can not change that the text is going into this one div.
The big picture of this it is about a collaborative text editor where the server takes care about the div where all text for all users is going and taking the edits from the users from the same div, posting and getting all changes using a live webrtc channel. On client side i can only change the style and attirbutes of the div which is controlled by the server.
The caret or cursor shall basically start and (as long as not moved by the user) stay at the bottom of the document.
I was able to do this with below example, but using position:relative, the div will grow in height on overflow (when we enter a lot of text). But when changing the position to absolute, the caret will start top left again.
https://jsfiddle.net/pa0owso5/20/
<html>
<style>
.canvas {
background-color: #fff;
box-shadow: 0 4px 14px -4px #919191;
border: 1px solid #e0e0e0;
height: 200px;
width: 400px;
margin: 20px;
padding-left: 20px;
padding-top: 20px;
padding-bottom: 20px;
padding-right: 20px;
word-wrap:break-word;
vertical-align: bottom;
display: table-cell;
word-wrap:break-word;
overflow: scroll;
vertical-align: bottom;
display: table-cell;
position:relative;
}
</style>
<div contenteditable=true class="canvas">
text should start bottom left
</div>
</html>
Key css elements i use currently are:
vertical-align: bottom;
display: table-cell;
word-wrap:break-word;
position:relative;
A:
With use of position:relative your caret is able to know where the "bottom" of your canvas is. If you use position:absolute on your canvas class, this means that you are "master of this canvas", but of course also that you have to set all values on your own. This, subsequently, means that your caret does not know automatically where bottom is.
Anyhow, you can add an additional "caret" class and give this class the information it needs to position itself.
Try following in CSS:
.canvas {
background-color: #fff;
box-shadow: 0 4px 14px -4px #919191;
border: 1px solid #e0e0e0;
height: 300px;
width: 500px;
margin: 20px;
padding-left: 20px;
padding-top: 20px;
padding-bottom: 20px;
padding-right: 20px;
word-wrap:break-word;
vertical-align: bottom;
display: table-cell;
word-wrap:break-word;
overflow: scroll;
vertical-align: bottom;
display: table-cell;
position:absolute;
}
.caret {
margin-top: 250px;
position: relative;
}
And in your HTML:
<div contenteditable=true class="canvas">
<div contenteditable=true class="caret">
testtext
</div>
</div>
Cheers!
|
[
"sharepoint.stackexchange",
"0000204283.txt"
] |
Q:
Is there a way to share the subsite link again?
I have moved a subsite to another location and would like to email all shared users a new url. Is it possible to "resend" the link to all current shared users as if they were just given permissions?
A:
On Sharepoint 2013/Online, when you hit on Share you will get the option to see who it's being shared with, right there you will see "send an email to everyone".
Anytime you are asking it is necessary you let people know what version of Sharepoint you are running since the answer will vary based on the version.
If you want the same email sent by Microsoft, I can't help you with that.
|
[
"stackoverflow",
"0000399482.txt"
] |
Q:
Can I change the height of a specified window's caption bar?
I want to self-draw the caption bar of my application's window, so I decided to override OnNcPaint() methods. But I don't know how to set a different height of the caption bar. Everytime I use GetSystemMetrics(SM_CYCAPTION), it retruns the same value.
Can anyone tell me how to do it? Thank you!
A:
You can't change the size of a normal Windows-drawn caption bar. That's determined by the user settings and the theme. If you're drawing things yourself, then you also define the caption dimensions yourself. You can paint whatever you want wherever you want, so you can paint your caption bar over what would normally be considered the client area. To make that extra region behave as though it's really the caption bar, handle the wm_NCHitTest message and return htCaption.
Note that GetSystemMetrics does not accept a window handle as one of its parameters. That means that it cannot return window-specific metrics. As its name suggests, it gives you system-wide metrics.
|
[
"stackoverflow",
"0051092207.txt"
] |
Q:
How to sudo bash keywords like [[
I want to test if a file exists. I don't have access to the directory without sudo.
if sudo [[ -f ~otheruser/.ssh/id_rsa ]]; then echo 'asdf'; fi
returns sudo: [[: command not found.
if sudo [ -f ~otheruser/.ssh/id_rsa ]; then echo 'asdf'; fi
or
if sudo test -f ~otheruser/.ssh/id_rsa; then echo 'asdf'; fi
both work.
I know this is because [[ is a bash keyword, while test and [ are builtins, meaning that we can do a='['; $a -f "~/.ssh/id_rsa" ] but not a='[['; $a -f "~/.ssh/id_rsa" ]] among other things. Is this another limitation? You're just not allowed to sudo bash keywords?
(All my information comes from SO answers because that's what google returns; sorry if there was a better spot to look.)
A:
Since [[ is Bash syntax, you can:
if sudo bash -c '[[ -f "some-file" ]]'; then
...
else
...
fi
sudo [ and sudo test works because they are also external commands:
/usr/bin/[
/usr/bin/test
|
[
"stackoverflow",
"0053380066.txt"
] |
Q:
Connection to MQTT Broker
I need to realize connection to broker. Now I'm connecting to public broker in the Internet (http://www.mqtt-dashboard.com/). I do it in the following way:
private static final String broker = "tcp://broker.mqttdashboard.com:1883"; //bridge and host
mqttClient = new MqttClient(broker, MqttClient.generateClientId(), new MemoryPersistence()); //URI, ClientId, Persistence
mqttClient.connect();
But how can I connect to the broker which I downloaded and which is on my computer? Tried to change tcp://broker.mqttdashboard.com on path to broker (such as E:\MQTT\rsmb_1.2.0_MQTT\windows\broker.exe), but it didn't help
A:
a broker is like a server, so you need to download the tool and configure the port on it,
after that you can launch it and connect to to it using something like "tcp://localhost:1883" as a network setting...
Or like @hardillb said
"mqtt://localhost:1883"
|
[
"stackoverflow",
"0015350077.txt"
] |
Q:
Error: Not allowed element when it is in JS
Just a quick validation question, I get:
document type does not allow element "div" here
And my code:
$('#wrapper').prepend('<div id="slider"></div>');
It's just a JS stuff, how do I handle this?
A:
I can't think of any time you would get that error in the middle of a piece of JavaScript unless you are using XHTML, in which case the short answer is: Stop using XHTML, start using HTML 4 or 5.
The reason you get the error is described in the XHTML 1.0 specification:
In XHTML, the script and style elements are declared as having #PCDATA content. As a result, < and & will be treated as the start of markup
The latest version of the XHTML Media Types note provides work–arounds:
DO use external scripts if your script uses < or & or ]]> or --. DO NOT embed a script in a document if it contains any of these characters.
and
If you must embed the content, the following patterns can be used:
<style>/*<![CDATA[*/
...
/*]]>*/</style>
This is all rather a lot of effort, and just switching to HTML is a simpler option. Browsers are designed for HTML and their XHTML support is provided as an afterthought. If you get any benefits from XHTML it will be from using it with server side tools as part of your publishing process … and not many people are doing that.
|
[
"stackoverflow",
"0047079739.txt"
] |
Q:
VS2017 compiles code that is syntactically incorrect, Intellisence missing
I get this strange behaviour from VS2017 working won C++ project:
Intellisence is missing - i just type plain text with no warnings, And it still compiles:
No errors are shown in the whole file. However, when i try the same everywhere outside this function's scope, everything works as expected:
The problem occurs in my generic function implementation:
#pragma region Public API
template <typename Key, typename Value>
void BinarySearchTree<Key, Value> ::Put(Key key, Value val)
{
Node node = root_;
if(node.key == null)
sadadasd
affsa
dasds
dasdsad
asdsad
}
#pragma endregion
Class defined like this:
template <typename Key, typename Value>
class BinarySearchTree {};
Again, it is dead silent - no red/yellow at all. Compiled code even runs. It is as if that part is comented out.
Tried reloading VS, did not help
A:
This is a known issue with Visual C++ that has existed for a long time. It does not implement two-phase lookup. It basically just completely skips over templates until they are instantiated. Apparently, they finally fixed it (at least partially).
https://blogs.msdn.microsoft.com/vcblog/2017/09/11/two-phase-name-lookup-support-comes-to-msvc/
A:
As per class template reference:
A class template by itself is not a type, or an object, or any other
entity. No code is generated from a source file that contains only
template definitions. In order for any code to appear, a template must
be instantiated...
Update: This appears to be a Visual C++ specific bug. Other compilers are likely to issue an error.
Trivial example for GCC
More info on the subject in this SO post:
What exactly is "broken" with Microsoft Visual C++'s two-phase template instantiation?
|
[
"stackoverflow",
"0052209553.txt"
] |
Q:
How can I get started with integrating AWS Amplify to a Nuxt.js project?
Im recently started working with vue and nuxt. I want to add an AWS backend to my project. I've seen that Amplify is useful but haven't been able to find any resources on how to implement it in nuxt. Any advice?
A:
I'm trying to implement as well AWS services as a backend for an app I'm working on.
I managed to get a basic setup working with my Nuxt app doing the following steps.
1.- Create a Amplify Plugin File. (plugins/amplify.js)
import Vue from 'vue'
import Amplify, * as AmplifyModules from 'aws-amplify'
import { AmplifyPlugin, components } from 'aws-amplify-vue'
import aws_exports from '@/aws-exports'
Amplify.configure(aws_exports)
Vue.use(AmplifyPlugin, AmplifyModules)
//register components individually for further use
// Do not import in .vue files
Vue.component('sign-in', components.SignIn)
2.- Import the plugin into the Nuxt Config.
plugins: [
{
src: '~plugins/amplify.js',
ssr: false
}
]
I'll try and elaborate further or maybe create a tutorial. Hope it helps!
|
[
"stackoverflow",
"0009376179.txt"
] |
Q:
xmessage to the active X window from cron
I have made cron commands like "go to sleep", "open window", "close window" etc. to pop out with xmessage using it's argument -display. Usually -display :0.0 produces the desired result but there are times when I use multiple X screens (:0.1, :0.2..) and therefore I miss these messages.
Is there a way to find out which X session is active in like that user is viewing that session at that very moment?
A:
Try with the commands who -t, or even just w
These commands will give you information about the console and the X server
|
[
"stackoverflow",
"0006403294.txt"
] |
Q:
How to calculate remaining space in local storage?
How do I find remaining/total space on the local storage?
Can I use StatFs for this (as in - How to Check available space on android device ? on SD card?)
A:
Turns out you can. Ran this code which seems to return the appropriate number of bytes remaining in my internal storage. Unsure about the reliability of Environment.getDataDirectory()
public static long remainingLocalStorage()
{
StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
stat.restat(Environment.getDataDirectory().getPath());
long bytesAvailable = (long)stat.getBlockSize() *(long)stat.getAvailableBlocks();
return bytesAvailable;
}
|
[
"stackoverflow",
"0029633104.txt"
] |
Q:
Caesar cipher code app for android
My question is how can I code 'space' to be just an empty space in the coded text , because now if I enter a text for example abc'space'abc I get the coded letters for abc and instead of space I get # but I want to get just an empty space...and also for the decode, the reverse function if I press space I get 7 but I want an empty space..I don't want to code space or decode him that's all the idea
public class MainActivity extends ActionBarActivity {
TextView myText, myText2;
Button myCodeButton, myDecodeButton, deleteButton;
public static EditText enteredEditText;
public String getText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myText = (TextView) findViewById(R.id.textView1);
myText2 = (TextView) findViewById(R.id.textView2);
enteredEditText = (EditText) findViewById(R.id.editText1);
myCodeButton = (Button) findViewById(R.id.button1);
myDecodeButton = (Button) findViewById(R.id.button2);
deleteButton = (Button) findViewById(R.id.button3);
Code_My_TextButton();
Decode_my_textButton();
// this is just for clearing edit_texts and text_views
deleteClick();
}
public void Code_My_TextButton()
{
myCodeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Caesar_cipher_coding_method();
myText2.setText("");
}
});
}
private void Caesar_cipher_coding_method() {
int shift = 3;
Editable msg = enteredEditText.getText();
String s = "";
int len = msg.length();
for (int x = 0; x < len; x++) {
char c = (char) (msg.charAt(x) + shift);
if (c > 'z' || (c > 'Z' && c < 'd'))
{
c -= 26;
}
s += c;
}
myText.setText(s);
}
public void Decode_my_textButton()
{
myDecodeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Reverse_Caesar_cipher_coding_method();
}
});
}
private void Reverse_Caesar_cipher_coding_method() {
int shift = -3;
Editable msg = enteredEditText.getText();
String s = "";
int len = msg.length();
for (int x = 0; x < len; x++) {
char c = (char) (msg.charAt(x) + shift);
if (c < 'A' || (c < 'a' && c > 'W'))
c += 26;
s += c;
}
myText2.setText(s);
myText.setText("");
}
// this is just for clearing edit_texts and text_views
public void deleteClick()
{
deleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
enteredEditText.setText("");
myText.setText("");
myText2.setText("");
}
});
}
}
A:
All you would have to do is check for it in both your loops like so:
for (int x = 0; x < len; x++) {
if (Character.isWhitespace(msg.charAt(x))) {
s += " ";
continue;
}
char c = (char) (msg.charAt(x) + 3);
if (c > 'z' || (c > 'Z' && c < 'd')) {
c -= 26;
}
s += c;
}
|
[
"stackoverflow",
"0001038584.txt"
] |
Q:
clear the text field or destroy the object
I have a text field, which holds the session value. Now while when i do logout operation.. clearing the text field does not work...
sessionHold.text = "";
The above code does not work, its not clearing the session value in the field.
appSes = event.result as Array
var vinoth:String = String(appSes[0]);
Alert.show(vinoth);
sessionHold.text = appSes[1];
Now i am slightly confused....
A:
why do you need to hold the session id inside a text field and not inside a String varialble ?!
|
[
"askubuntu",
"0000377050.txt"
] |
Q:
How do I get Mediatek MT7630E 802.11bgn Wi-Fi Adapter working?
It worked with the pre-installed Ubuntu, but after re-installing Ubuntu dual-boot with Windows 8.1, the WiFi is not working.
Is there a driver for this adapter that will work on Ubuntu 12.04?
A:
A better solution is to install the driver using DKMS. This way you won't need to re-install it after kernel uprades. Do it this way:
sudo apt-get install git dkms build-essential
git clone https://github.com/neurobin/MT7630E.git
cd MT7630E/
sudo make dkms
A:
Open a terminal (Ctrl+Alt+T), then run the following commands:
sudo apt-get install git build-essential
git clone https://github.com/neurobin/MT7630E.git
cd MT7630E/
chmod +x install test uninstall
sudo ./install
Works like a charm for me (Asus TP300LD).
|
[
"math.stackexchange",
"0000459935.txt"
] |
Q:
Topological Dynamics: closure of forward orbit vs. $\omega$ limit set
Let $f: X \rightarrow X$ be continuous, where $X$ is a topological space. This forms a topological dynamical system. For $x \in X$, define $\omega (x) = \cap_{n \in \mathbb{N}} \overline{\cup_{i \geq n}f^{i}(x)}$. Define the forward orbit of $x$ to be $\mathcal{O}^{+}(x) = \cup_{n \in \mathbb{N}} f^{n}(x)$. Clearly $\omega (x) \subseteq \overline{\mathcal{O}^{+}(x)}$. My intuition is that $\overline{\mathcal{O}^{+}(x)} - \mathcal{O}^{+}(x) \subseteq \omega (x)$ also holds. Is this true? The closures of two sets that only differ in a finite number of points should be the same, but this reasoning can't be used because we're dealing with an infinite intersection..
What I've tried:
Say $z \in \overline{\mathcal{O}^{+}(x)} - \mathcal{O}^{+}(x)$. Then every nbhd $U$ of $z$ contains some $f^{j}(x)$. Fixing $n$, it suffices to show that $z \in \overline{\cup_{i \geq n}f^{i}(x)}$, i.e. that every nbhd $U$ of $z$ also contains some $f^{i}(x)$ for $i \geq n$. Could there be some funky nbhd of $z$ that contains some iterate $f^{k}(x)$ for $k < n$ but never any for $k \geq n$?
For some context, my larger question is: "Is $\overline{\mathcal{O}^{+}(x)}$ f-invariant?" which I think will follow from the answer to the above, since $\omega$-limit sets are $f$-invariant.
Thank you for any help/advice!
A:
The accepted answer is still not true given your (lack of) hypotheses. You need your space to be at least $T_1$. Heuristically, $\omega(x)$ is the set of points for which the orbit of $x$ under $f$ approaches infinitely often and $\overline{O^{+}(x)}-O^{+}(x)$ is the set of points for which the orbit approaches (but does not meet). Your intuition is right, that the set of points that the $x$ visits often under $f$ should be visited infinitely often, but that relies on the $T_1$ characterization of a limit point $p$ of a set $S$: that every neighborhood of $p$ contains infinitely many members of $S$. Regrettably, in a general topological space, a limit point $p$ of a set $S$ only implies that every neighborhood of $p$ contains a member of $S$.
With that in mind, consider the natural numbers with two zeros. That is, let $\tilde{\mathbb{N}}=\mathbb{N}\cup\{*\}$, and let $\{0,*\}$ and the singletons be a basis for your topology. So $0$ and $*$ are topologically indistinguishable.
Define a function $f:\mathbb{N}\to \mathbb{N}$ by letting $f(n)=n+1$ if $n\in \mathbb{N}$ and $f(*)=1$. The pre-image of every basic open set is open, and so $f$ is continuous. With that said, $O^{+}(0)=\mathbb{N}$ and $\overline{O^{+}(0)}\setminus O^{+}(0)=\tilde{\mathbb{N}}\setminus \mathbb{N}=\{*\}$. Moreover, by the same argument in my other answer above/below, $\omega(x)=\emptyset$, the key in this part being the fact that $*$ lies in the closure of the orbit of $0$ but not $f(0)=1$. Since $\{*\}\not\subseteq \emptyset$, this completes the counterexample.
However, since every space you might care about is most likely $T_1$, this is probably not an issue for you.
A:
The first question is false, as pointed out. The larger question is true however. Indeed, let $y \in \overline{\mathcal{O}^{+}(x)}$ : then there exists integers $n_k$ such that $f^{n_k}(x)$ converges to $y$, by definition. But then $f^{n_k +1}(x)$ converges to $f(y)$ (by continuity of $f$) so $f(y) \in \overline{\mathcal{O}^{+}(x)}$ as well.
It does not imply the first question, because you can perfectly well have two $f$-invariant closed sets $A \subset B$ without having $A=B$ (take $f(x)=x/2$, $A=\{0 \}$, $B=\{1/2^n \} \cup \{0 \}$).
The property "$B$ is a close $f$-invariant set that does not contain any other $f$-invariant set" is called irreducibility.
|
[
"stackoverflow",
"0043636683.txt"
] |
Q:
How to code for a new window
how can I code for a new window? I have a button that creates a new one but I like to code for it and I don't know how. I think I must define the new window in any way but I don't know how to do this because for opening a new window with help of a button you must define the window self, but no name.
Thanks for helping!
I have create the button and its command in this way:
from Tkinter import *
import Tkinter as tk
master = tk.Tk()
def create_window(): #Definion und Festlegung neues Fenster
toplevel = Toplevel()
toplevel.title('result')
toplevel.geometry('1500x1000')
toplevel.focus_set()
Button(master, text='forward', command=create_window).pack(padx=5, anchor=N, pady=4)
master.mainloop()
A:
Coding for the new window (or creating widgets in the new window) is similar to how you do it in the main window. Just pass the new window (toplevel) as the parent.
Here is an example that creates a Label and an Entry widgets in the new window.
from Tkinter import *
import Tkinter as tk
master = tk.Tk() # Create the main window
def create_window(): #Definion und Festlegung neues Fenster
toplevel = Toplevel()
toplevel.title('result')
toplevel.geometry('1500x1000')
# Create widges in the new window
label = tk.Label(toplevel, text="A Label", fg='blue')
entry = tk.Entry(toplevel)
label.pack()
entry.pack()
toplevel.focus_set()
Button(master, text='forward', command=create_window).pack(padx=5, anchor=N, pady=4)
master.mainloop()
|
[
"workplace.stackexchange",
"0000033154.txt"
] |
Q:
Boss asked me to copy files from ex-CEOs computer
There has recently been a change in the corporate hierarchy. The former CEO/President is now, technically, just an employee (although, to be sure, an employee with a lot of weight) and a shareholder. The new CEO/President has asked me to copy some documents from the ex-CEOs laptop discreetly and without anyone's knowledge. Additionally, the request was made verbally, and I have no documentation to back me up if I get caught.
It feels wrong to me... you know, the whole, "with great power..." kind of thing.
My questions are:
Is there any reason to believe that this a legitimate request?
What can I do to protect myself and ensure my actions are legal?
A:
What a quandary! In the US, a company owns the network and the data transmitted across it. Additionally, if the former CEO's laptop was issued by the company, the company has complete access to it as well. Legally, you should be fine following the direction from you new CEO, but get that direction in writing.
If you don't get the direction in writing, then your work could be characterized as hacking. Think about it like this: if your company tells you to get the data, it's safe; if you go to get the data on your own, it's a crime. It is very possible that the new CEO is simply curious about the data, and if you are caught and don't have written permission to get the data, he could easily throw you under the bus. In this case, denying he asked you to get the information and then telling the authorities that you committed a hacking crime.
Now, ethics. If your company's new CEO is asking you to gather the information in a manner that feels wrong, it probably is. When reviewing electronic records, companies usually maintain a chain-of-evidence that starts with the original request for data in writing. Once that is done, the request gets approved by Legal, and then you go to work. The request can be as simple as "get the data" or as explicit as "all e-mails from date a to date b, and install a keylogger". Once you get the data, you treat it as evidence and strictly follow legal's requirements for maintaining the chain of evidence.
In your case, your new CEO asked you to pull data from the old CEO's laptop in a manner that suggests he doesn't care about the chain-of-evidence. He also asked you to do so in a manner that is dangerous for you if you are caught. I would ask for the request in writing, or not do it all. In fact, if the worst thing happens and he fires you for not getting the information, at least you'll be unemployed and not in jail.
A:
I have been in this position before, and while it could be something illegal or unethical, it could just as well be a perfectly legitimate request with a legitimate reason.
When someone in a high access position like this leaves their position, there's often legitimate concern that he/she will destroy company data that they feel entitled to (or want to deny the company), and/or use that company data in their next role to undermine their former employer or for personal gain (think poaching customers, or bringing business relationships with them to the next place). Obviously, making sure this doesn't happen is a matter that must be dealt with discretely, as tipping the person off will only make it happen faster, and generally speaking, no one wants these suspicions to be common knowledge.
You could ask for written permission... but that would probably conflict with the goal of discretion, and especially if it's a company owned laptop, in the US, that data belongs to the company, not the ex-employee, regardless of his position. So the company's agents (the new CEO) are legally entitled to that data, and allowed to be as discrete or as obvious as they want about getting it.
My advice to you is that rather than just copying the files requested, is to take a backup of the laptop, with whatever means you have at your disposal and document the request and process. (Disk image, same software you use to backup your servers, scripted robocopy or whatever.) Compared to a targeted copying of important files, backing up an executive's machine when they leave is hard to frame as snooping or unauthorized access, which makes it difficult for you to get thrown under the bus, especially if you keep a written record of what you did when you did it, and at whose request. In this case, you would then give the backup to the new CEO, and instruct him on how to search and extract the files he wants. That way if there's any malfeasance going on, you just did what a good IT guy does, and made backups, while the new CEO was the one who went snooping through the backups.
And, going forward, it's a good idea to get this process enshrined in an official policy - it protects you from any accusations if it's just the normal process, and every now and then, you'll get to be the hero when you can pull the critical files that some ex-employee had on their machine that no one knew they were missing, until they need them, NOW.
A:
Who owns the former CEO's laptop? If it's a corporate laptop then the documents on it are also the property of the company, assuming your legal team were sober when they wrote/reviewed your acceptable use policy.
It might not be pleasant to have to sneak around to do this but it's certainly not a legal issue, and possibly not even an ethical one.
|
[
"stackoverflow",
"0000085183.txt"
] |
Q:
Windsor Container: How to force dispose of an object?
I have an object that implements IDisposable that is registered with the Windsor Container and I would like to dispose of it so it's Dispose method is called and next time Resolve is called it fetches a new instance.
Does
container.Release(obj);
automatically call Dispose() immediately? Or do I need to do
obj.Dispose();
container.Release(obj);
Couldn't find anything in the documentation on what exactly Release does
EDIT:
See my answer below for the results of tests I ran. Now the question becomes, how do I force the container to release an instance of a component with a singleton lifecycle? This only needs to be done in one place and writing a custom lifecycle seems far too heavyweight, is there no built in way of doing it?
A:
This is something I think people aren't really aware of when working with the Windsor container - especially the often surprising behavior that disposable transient components are held onto by the container for the lifetime of the kernel until it's disposed unless you release them yourself - though it is documented - take a look here - but to quickly quote:
the MicroKernel has a pluggable release policy that can hook up and implement some
routing to dispose the components. The MicroKernel comes with three IReleasePolicy implementations:
AllComponentsReleasePolicy: track all components to enforce correct disposal upon the MicroKernel instance disposal
LifecycledComponentsReleasePolicy: only track components that have a decommission lifecycle associated
NoTrackingReleasePolicy: does not perform any tracking
You can also implement your own release policy by using the interface IReleasePolicy.
What you might find easier is to change the policy to a NoTrackingReleasePolicy and then handle the disposing yourself - this is potentially risky as well, but if your lifestyles are largely transient (or if when your container is disposed your application is about to close anyway) it's probably not a big deal. Remember however that any components which have already been injected with the singleton will hold a reference, so you could end up causing problems trying to "refresh" your singletons - it seems like a bad practice, and I wonder if perhaps you can avoid having to do this in the first place by improving the way your applications put together.
Other approaches are to build a custom lifecycle with it's own decommission implementation (so releasing the singleton would actually dispose of the component, much like the transient lifecycle does).
Alternatively another approach is to have a decorator for your service registered in the container with a singleton lifestyle, but your actual underlying service registered in the container with a transient lifestyle - then when you need to refresh the component just dispose of the transient underlying component held by the decorator and replace it with a freshly resolved instance (resolve it using the components key, rather then the service, to avoid getting the decorator) - this avoids issues with other singleton services (which aren't being "refreshed") from holding onto stale services which have been disposed of making them unusable, but does require a bit of casting etc. to make it work.
A:
It depends on the lifestyle of the component you specified when you added it to the container.
You would use Release() If the lifestyle is Pooled. This puts the component back in the pool for the next retrieval (the object is not destroyed, so disposing would be bad)
if the lifestyle is transient, a new object is created when you get the component. In this case the disposal is up to you, and you do not need to call Release
If the lifestyle is Thread, the same component is used for each thread, not destroyed.
If the lifestyle is Singleton, only one component is created and not detroyed.
Most likely, you are using transient components? (if you are concerned about disposing of them in a timely manner)
in that case, just wrap it with a using and you're set (or call the dispose yourself somewhere)
using(ISomeService service = container.Resolve<ISomeService>())
{
// Do stuff here
// service.Dispose is automatically called
}
Edit - Yes, in order to "refresh" or dispose and recreate your singleton you would need to either destroy the container or write a custom lifecycle. Doing a custom lifecycle is not actually that difficult and keeps the logic to do so in one place.
|
[
"stackoverflow",
"0046203498.txt"
] |
Q:
Convert binary to signed int/decimal
I am trying to convert hex data to signed int/decimal and can't figure out what I'm doing wrong.
I need FE to turn into -2.
I'm using Convert.ToInt32(fields[10], 16) but am getting 254 instead of -2.
Any assistance would be greatly appreciated.
A:
int is 32 bits wide, so 0xFE is REALLY being interpreted as 0x000000FE for the purposes of Convert.ToInt32(string, int), which is equal to 254 in the space of int.
Since you're wanting to work with a signed byte range of values , use Convert.ToSByte(string, int) instead (byte is unsigned by default, so you need the sbyte type instead).
Convert.ToSByte("FE",16)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.