id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_unix.387118
I have a ubuntu server with two ethernet cards, eth0 and eth1, and plan to use it as a DHCP server to create two different subnets, 192.168.10.0/255.255.255.0 and 192.168.100.0/255.255.255.0.Is it possible NOT to set the static address for eth0 and eth1 individually on the file /etc/network/interfaces and make the DHCP server work in any other case?
How to set dhcp server for multiple interface?
isc dhcpd
null
_webmaster.87135
I buy a old domain name and I am going to start new blog on it.Currently, it has more than 100 pages indexed by Google.How to remove all of them before start my site?
Buy new domain, how remove already indexed pages?
seo;domains
null
_unix.125016
I'm a newbie at Encfs.After I read a paper about Encfs, I figured out there is a Encryption layer in Encfs.So I tried to find exact encryption function. but I couldn't find that because there are many functions. Does anyone have any idea or advice?
What is the encryption function in Encfs?
filesystems;encryption;fuse;encfs
null
_unix.356034
I am a beginner in linux and i have only used ubuntu (with unit and gnome as DE).I have heard people saying that ubuntu are for beginners and advanced users use fedora, open suse or arch.But all the difference i have seen is that the desktop environments are different and the package managers are different(ubuntu using apt, fedora using yum and arch using packman).so my question is how are these distributions different if we fix the above lying DE(which interacts with the user) to gnome?What is the actual difference apart from the desktop environment between different distributions of linux?
what is the exact difference between different distributions?
distributions
Distributions usually start with a philosophy: to provide the most stable desktop, to provide the newest packages, to be the best Do-It-Yourself distribution, to fix the problems in another distribution, to be the best long-term-supported server distribution and so on. The packages, their versions, and any distro-specific behaviors (like the package manager) all fall out from that basic philosophy.If you're looking for the right distribution for you, you should look for the one whose philosophy matches your own requirements or desires. Detailed comparisons of the specific differences between individual releases of distributions tend to be short-lived as each distro rolls to a new version (and therefore a bad fit for Stack Exchange answers).
_unix.314199
Under XFCE, xdg-open calls exo-open. When exo-open is called with --launch is uses the application set with xfce4-settings-manager.However, when one calls exo-open foo.txt (local path, without --launch), how is the corresponding application selected?
What is the selected application for XFCE's exo-open?
xfce;file opening
null
_softwareengineering.284402
First of all, the basics.N-tier application: presentation, business layer, database. It is an old .NET 2.0 (WSE + WinForms) application, a bit more tightly coupled than I'd like, and the requirement is to upgrade it to a newer architecture, while at the same time eliminating the less-than-ideal design choices made 10+ years ago (e.g. use DTOs instead of datatables/DB views directly on the client etc.).I'm thinking of going by the following design, in broad strokes: Create a business logic layer class that will include all business logic, validations etc., using a data access class for CRUD operations.Expose this BLL using a WCF service layer as a wrapper for its methods.Consume the WCF service by the new client (WPF probably).To centralize all WCF-related operations in the client project, I will create a helper class that handles the connection to the WCF service and acts like a Faade to the service operations. Now, at the same time, there will be a new Web application (MVC) that will use some of the operations defined in the BLL. However, due to outsourcing and other reasons out of the scope of this question, what I particularly don't want is for the MVC controller developer to use (or even know of) e.g. BLLAssembly.WCFOnlyMethod(). Conversely, I wouldn't want the WCF service developer to be able to use BLLAssembly.WebOnlyMethod(). I guess both of those cases can be covered by using conditional compilation symbols in the BLL assembly (e.g. WEB_ONLY / WCF_ONLY), but of course this means two different versions of it, one for each project.So, my question is: Given the fact that there will be a single BLL in order to maximize code reuse, what is the optimal approach for referencing the BLL from the WCF service and the MVC controller?The WCF service will have a hard-reference to the BLL, that much I can say with relative certainty. Client-side, the helper class will have a reference to the WCF service interface, which will be implemented by the proxy. That way the WPF client is not affected by internal changes in the BLL, as it should be.Should the MVC controller have a hard-reference to (its version of) the BLL assembly as well?Should I use a WCF service for the MVC project, as discussed here (Is this breaking SOA?) or is that overkill? The production server(s) will be the same for both projects.Should I have the MVC controller reference an interface, instead of the actual BLL assembly? I would still need to instantiate an actual class implementing that interface, of course, so somehow the assembly should be passed to the MVC project... or I could use a WCF service (see above).Or should I abandon the notion of a common BLL between the projects altogether?Thanks in advance for any advice.
Advice on architecture (WCF / MVC)
architecture;mvc;wcf;service
You can have a common BLL component, exposed as a web service quite happily. Simply expose 2 interfaces on the WCF side of things that are implemented by the same methods in the BLL. Both thick clients and the MVC website will make calls to this common WCF webservice, but each using a different interface.So you have a Website only web service the web site can call, and another one for the thick clients. Only allow the website devs to access the first service by not giving them the security keys to access it - you'll have some form of security to prevent unauthorised users but you'll also have some for of security to restrict access to rogue applications too.
_softwareengineering.246339
What is the best practice, when it comes to views' translation in MVC design pattern, in multilingual website:Always have only one view file and translate its particular strings with a framework translation function.Always have as many views as website supports, directly translated, one for each language, and let framework internals load particular language-specific view file for language currently selected by user.Which of these two options should I use (if there isn't any third one) and why?
Translating views in MVC
mvc;view;translate
The proper choice is using the single view with the strings stored in the appropriate localization framework for the view.There are two main reasons for this:It's DRY. There is one view that is used for all the languages. Consider the joys you will have when you need to change the layout on the view if you have one for each language... you've likely got English and then the FIGS set... and possibly CJK too... That's eight copies of the same view. You're going to miss one and you're going to make a mistake in another one. One view.The industry behind localization is based on taking a file of strings and translating that file. You might have this person in house instead... either way, they aren't programers. The markup for the view itself - be it php, jsp, erb, or a chunk of javascript. You don't want to be sending them your code, and you don't want them making mistakes in translating your variables, styles, and structures (<font color=black>test</font> becomes <fuente colorido=negro>prueba</fuente>). You, the programmer understand what needs to be translated and what does and giving just this to the person doing the translation makes it less likely to introduce errors.Use the localization framework. It will make it easier for you, it will make it easier for the person doing the translations.
_codereview.73838
This is a follow up to:Messenger supporting notifications and requestsShoot the Messenger pt. 2I've written a lightweight (I think) class that acts as a messenger service between classes for both notifications (fire and forget updates to other classes) and requests (a notification sent out that expects a returned value).Since the last question, I've extracted two interfaces out of the messenger, IMessenger, that handles sending and receiving messages and IRequester, that handles sending and receiving requests.IMessenger/// <summary>/// Interface for strongly-typed messengers./// </summary>public interface IMessenger{ /// <summary> /// Register an action for a message. /// </summary> /// <typeparam name=T> Type of message to receive. </typeparam> /// <param name=action> The action that happens when the message is received. </param> void Register<T>(Action<T> action); /// <summary> /// Sends the specified message. /// </summary> /// <typeparam name=T> The type of message to send. </typeparam> /// <param name=message> The message to send. </param> void Send<T>(T message); /// <summary> /// Unregister an action. /// </summary> /// <typeparam name=T> The type of messag to unregister from. </typeparam> /// <param name=action> The action to unregister. </param> void Unregister<T>(Action<T> action);}IRequester/// <summary>/// Interface for strongly-typed central hubs that support anonymous registry of functions to handle requests./// </summary>public interface IRequester{ /// <summary> /// Register a function for a request message. /// </summary> /// <remarks> /// Request messages have a return value. /// </remarks> /// <typeparam name=T> Type of message to receive. </typeparam> /// <typeparam name=R> Return type of the request. </typeparam> /// <param name=request> The function that fulfils the request. </param> void Register<T, R>(Func<T, R> request); /// <summary> /// Send a request. /// </summary> /// <typeparam name=T> The type of the parameter of the request. </typeparam> /// <typeparam name=R> The return type of the request. </typeparam> /// <param name=parameter> The parameter. </param> /// <returns> The result of the request. </returns> IEnumerable<R> Request<T, R>(T parameter); /// <summary> /// Unregister a request. /// </summary> /// <typeparam name=T> The type of request to unregister. </typeparam> /// <typeparam name=R> The return type of the request. </typeparam> /// <param name=request> The request to unregister. </param> void Unregister<T, R>(Func<T, R> request);}I've made the instance variables use interfaces instead of concrete types for more flexibility down the line, and I've cached the typeof(T) operation instead of calling it multiple times.I've also filled out the comments to better represent what was going on and correctly marked my instance collections as readonly.Messenger/// <summary>/// Strongly-typed messenger that also allows for IoC Service Locator requesting./// </summary>public class Messenger : IMessenger, IRequester{ /// <summary> /// The actions. These are called when a message is sent. /// </summary> private readonly IDictionary<Type, Delegate> actions = new Dictionary<Type, Delegate>(); /// <summary> /// The functions. These are called when a request is sent. /// </summary> private readonly IDictionary<Type, ICollection<Delegate>> functions = new Dictionary<Type, ICollection<Delegate>>(); /// <summary> /// Register a function for a request message. /// </summary> /// <remarks> /// Request messages have a return value. /// </remarks> /// <typeparam name=T> Type of message to receive. </typeparam> /// <typeparam name=R> Return type of the request. </typeparam> /// <param name=request> The function that fulfils the request. </param> public void Register<T, R>(Func<T, R> request) { if (request == null) { throw new ArgumentNullException(request); } var requestType = typeof(T); if (functions.ContainsKey(requestType)) { functions[requestType].Add(request); } else { functions.Add(requestType, new Collection<Delegate>() { request }); } } /// <summary> /// Register an action for a message. /// </summary> /// <typeparam name=T> Type of message to receive. </typeparam> /// <param name=action> The action that is executed when the message is received. </param> public void Register<T>(Action<T> action) { if (action == null) { throw new ArgumentNullException(action); } var messageType = typeof(T); if (actions.ContainsKey(messageType)) { actions[messageType] = Delegate.Combine(actions[messageType], action); } else { actions.Add(messageType, action); } } /// <summary> /// Send a request. /// </summary> /// <typeparam name=T>The type of request being sent.</typeparam> /// <typeparam name=R>Return type of the request.</typeparam> /// <param name=parameter>The parameter for the request.</param> /// <returns> A collection of results from the request. </returns> public IEnumerable<R> Request<T, R>(T parameter) { var requestType = typeof(T); if (functions.ContainsKey(requestType)) { var applicableFunctions = functions[requestType].OfType<Func<T, R>>(); foreach (var function in applicableFunctions) { yield return function(parameter); } } } /// <summary> /// Sends the specified message. /// </summary> /// <typeparam name=T> The type of message. </typeparam> /// <param name=message> The message to send. </param> public void Send<T>(T message) { var messageType = typeof(T); if (actions.ContainsKey(messageType)) { ((Action<T>)actions[messageType])(message); } } /// <summary> /// Unregister from a request. /// </summary> /// <typeparam name=T> The type of request to unregister from. </typeparam> /// <typeparam name=R> The return type of the request to unregister from. </typeparam> /// <param name=request> The request to unregister. </param> public void Unregister<T, R>(Func<T, R> request) { var requestType = typeof(T); if (functions.ContainsKey(requestType) && functions[requestType].Contains(request)) { functions[requestType].Remove(request); } } /// <summary> /// Unregister an action. /// </summary> /// <typeparam name=T> The type of message. </typeparam> /// <param name=action> The action to unregister. </param> public void Unregister<T>(Action<T> action) { var messageType = typeof(T); if (actions.ContainsKey(messageType)) { actions[messageType] = (Action<T>)Delegate.Remove(actions[messageType], action); } }}Example UsageUnchanged from before:public class Receiver{ public Receiver(Messenger messenger) { messenger.Register<string>(x => { Console.WriteLine(x); }); messenger.Register<string, string>(x => { if (x == hello) { return world; } return who are you?; }); messenger.Register<string, string>(x => { if (x == world) { return hello; } return what are you?; }); }}public class Sender{ public Sender(Messenger messenger) { messenger.Send<string>(Hello world!); Console.WriteLine(); foreach (string result in messenger.Request<string, string>(hello)) { Console.WriteLine(result); } Console.WriteLine(); foreach (string result in messenger.Request<string, string>(world)) { Console.WriteLine(result); } }}
Shoot the Messenger Part 3
c#
I would implement those interfaces in separate classes. I see no interaction between the two implementations in your Messenger class, and they seem like two separate entities with different purpose. So there should be no reason to mix them into a single class. Have you considered using interfaces instead of Actions? Something like:interface IMessenger{ void Register<T>(IReceiver<T> receiver); ...}interface IReceiver<T>{ void Handle(T message);}It requires some extra code to be written to register something, but it saves a lot of time debugging stuff, because you will work with strong types, instead of some arbitrary actions. At least in my experience (i used both approaches).I think any implementation of events aggregator must be thread-safe. Users of your interface will not be able to do the proper synchronization themselves. And your implementation will crash as soon there will be more than one thread in your application. :)It is usually a good idea to add a constraint to message type. Force your messages to implement some IMessage interface. This way you can a) easily find all the messages, that are currently in use, and b) forbid users of your interface to do this:messenger.Send<string>(Hello world!);//ormessenger.Send<int>(13);Can you guees what those messages represent? I know i can't. :) This is way better in my opinion:messenger.Send<WarningMessage>(new WariningMessage(The world is in danger!));//ormessenger.Send<UserChangedMessage>(new UserChangedMessage { UserId = 13 });
_unix.292384
I have a file which has a few lines.onetwothreefourfiveI need to add hostname of the server I'm working on as the first line of the file.For example if abcd555.india.com is the server, the output file should be like :abcd555.india.comonetwothreefourfiveHope my question is clear! I would be grateful to anyone who helps me out in this hour of need.
How to add hostname as first line of a file
vi;hostname;editors;columns
null
_unix.252672
I would like to change a LUKS password. I want to remove my old password, but I would like to try out my new password before removing the original. I obviously know the old password. I would like to use the terminal not GUI.I have sensitive data on the drive and would rather not have to use my backup so I need the method to be safe.
How do I change a LUKS password?
command line;password;luks
In LUKS scheme, you have 8 slots for passwords or key files. First, check, which of them are used:cryptsetup luksDump /dev/<device> |grep BLEDThen you can add, change or delete chosen keys:cryptsetup luksAddKey /dev/<device> (/path/to/<additionalkeyfile>) cryptsetup luksChangeKey /dev/<device> -S 6As for deleting keys, you have 2 options:a) delete any key that matches your entered password:cryptsetup luksRemoveKey /dev/<device>b) delete a key in specified slot:cryptsetup luksKillSlot /dev/<device> 6
_unix.208321
I installed centos 7.1 on bare metal (dual boot with windows), with encrypted disk. Installed a few things (oracle java) and did a full yum updateNow the system keeps booting to a console emergency mode.Welcome to emergency mode! After logging in, type journalctl -xb to viewsystem logs, systemctl reboot to reboot, systemctl default to try againto boot into default mode.Give root password for maintenance(or type Control-D to continue):journalctl didn't reveal anything salient. systemctl default causes it to come back to the emergency mode.After the update, there are two version of the kernel. Both go into emergency mode. I was able to boot with the rescue kernel (gnome even comes up - looks normal).The only error I can find is in dmesg:[ 16.434472] BUG: scheduling while atomic: swapper/0/0/0x10000100[ 16.434510] Modules linked in: sr_mod sd_mod cdrom crc_t10dif radeon(+) crct10dif_pclmul crct10dif_common crc32_pclmul crc32c_intel i2c_algo_bit drm_kms_helper ghash_clmulni_intel ttm aesni_intel ahci lrw libahci gf128mul e1000e glue_helper drm libata ablk_helper firewire_ohci cryptd firewire_core crc_itu_t ptp i2c_core pps_core wmi video hid_logitech_dj sunrpc dm_mirror dm_region_hash dm_log dm_mod[ 16.434515] CPU: 0 PID: 0 Comm: swapper/0 Not tainted 3.10.0-229.el7.x86_64 #1[ 16.434516] Hardware name: Dell Inc. Precision M4700/0DK7DT, BIOS A02 07/30/2012[ 16.434523] ffffffff818fc000 d91481999c9601df ffff88042dc03c58 ffffffff81604b0a[ 16.434527] ffff88042dc03c68 ffffffff815fec34 ffff88042dc03cc8 ffffffff81609d64[ 16.434531] ffffffff818fffd8 0000000000013680 ffffffff818fffd8 0000000000013680[ 16.434532] Call Trace:[ 16.434549] <IRQ> [<ffffffff81604b0a>] dump_stack+0x19/0x1b[ 16.434554] [<ffffffff815fec34>] __schedule_bug+0x4d/0x5b[ 16.434559] [<ffffffff81609d64>] __schedule+0x704/0x7b0[ 16.434568] [<ffffffff810a6876>] __cond_resched+0x26/0x30[ 16.434573] [<ffffffff8160a21a>] _cond_resched+0x3a/0x50[ 16.434578] [<ffffffff811ac9b5>] __kmalloc+0x55/0x230[ 16.434586] [<ffffffff814b61c8>] ? hid_alloc_report_buf+0x28/0x30[ 16.434591] [<ffffffff814b61c8>] hid_alloc_report_buf+0x28/0x30[ 16.434600] [<ffffffffa009e454>] logi_dj_ll_input_event+0xb4/0x1c0 [hid_logitech_dj][ 16.434608] [<ffffffff8146a24e>] input_handle_event+0x8e/0x520[ 16.434613] [<ffffffff8146a7e4>] input_inject_event+0x94/0xb0[ 16.434620] [<ffffffff8139c260>] ? kd_nosound+0x30/0x30[ 16.434625] [<ffffffff8139c2b2>] kbd_update_leds_helper+0x52/0x80[ 16.434631] [<ffffffff81467256>] input_handler_for_each_handle+0x66/0xa0[ 16.434635] [<ffffffff8139c889>] kbd_bh+0x89/0xb0[ 16.434642] [<ffffffff81077a3d>] tasklet_action+0x7d/0x140[ 16.434647] [<ffffffff81077bf7>] __do_softirq+0xf7/0x290[ 16.434654] [<ffffffff8161635c>] call_softirq+0x1c/0x30[ 16.434663] [<ffffffff81015de5>] do_softirq+0x55/0x90[ 16.434667] [<ffffffff81077f95>] irq_exit+0x115/0x120[ 16.434671] [<ffffffff81616ef8>] do_IRQ+0x58/0xf0[ 16.434676] [<ffffffff8160c0ed>] common_interrupt+0x6d/0x6d[ 16.434686] <EOI> [<ffffffff8133d707>] ? acpi_os_execute_deferred+0x1d/0x20[ 16.434693] [<ffffffff814aa6e2>] ? cpuidle_enter_state+0x52/0xc0[ 16.434698] [<ffffffff814aa815>] cpuidle_idle_call+0xc5/0x200[ 16.434704] [<ffffffff8101d21e>] arch_cpu_idle+0xe/0x30[ 16.434710] [<ffffffff810c6955>] cpu_startup_entry+0xf5/0x290[ 16.434716] [<ffffffff815f2fb7>] rest_init+0x77/0x80[ 16.434723] [<ffffffff81a45057>] start_kernel+0x429/0x44a[ 16.434728] [<ffffffff81a44a37>] ? repair_env_string+0x5c/0x5c[ 16.434733] [<ffffffff81a44120>] ? early_idt_handlers+0x120/0x120[ 16.434738] [<ffffffff81a445ee>] x86_64_start_reservations+0x2a/0x2c[ 16.434743] [<ffffffff81a44742>] x86_64_start_kernel+0x152/0x175Not sure this is the cause or not.What else should I look at?edit: also found this in journalctl, not sure this is relevant Jun 08 05:12:44 localhost kernel: firewire_ohci 0000:0c:00.0: register access failureJun 08 05:12:44 localhost kernel: firewire_ohci 0000:0c:00.0: added OHCI v1.10 device as card 0, 8 IR + 8 IT contexts, quirks 0x10Jun...Jun 08 05:12:42 localhost kernel: acpi PNP0A08:00: _OSC failed (AE_ERROR); disabling ASPM
fresh centos 7.1 install continually boots into emergency mode
centos;boot
null
_unix.108897
I have a windows 8.1 on which I installed Ubuntu 12.04 (dual OS). Now I also want to install Arch Linux alongside windows and ubuntu. Please tell me the how to do this on Ubuntu. I have a gparted Partion Editor. Also I installed the Arch linux which took me 24 minutes. But uploading it is taking forever. Am I on the right track? Please explain what to do next.
Install Arch Linux alongside Ubuntu 12.04
linux;ubuntu;arch linux
If Arch is installed at this point and you don't see it, then you only need to add a grub entry for Arch so that Grub would redirect you to the OS.If it is not installed, then you should follow the Arch installation guide up to the point of configuring GRUB and then you could check the GRUB page on the ArchWiki especially the dual booting section:https://wiki.archlinux.org/index.php/GRUB#Dual-booting
_computergraphics.98
I'm looking to use my GPU for non-graphical calculations (artificial life simulations) but ideally I would like to leave this running for weeks at a time, 24 hours a day.Is there anything I should take into account before trying this? Is a GPU subject to overheating or shortening of its lifespan by continuous use?What about the computer in general (it's a laptop in my case, but I'm interested in the differences in case it's worth me getting a desktop computer for this)? Will running the GPU non-stop place any strain on connected parts of the computer? Are there known problems that result from this?
Is long term continuous use of GPGPU safe for my GPU?
gpu
Running a GPU at full capacity will reduce its lifespan through electromigration; the speed at which the chips are damaged depends on how hot it is.A desktop computer has enough room that the designer can put in a cooling system to handle the worst-case thermal situation. Running your GPU at continuous full load won't overheat it too badly, and you can expect it to last several years.A laptop, on the other hand, is strongly space-constrained. Typically, the cooling system is designed to handle brief bursts of heat interspersed with long periods of near-idle operation. You may not be able to run it at full load 24/7: the BIOS or operating system will slow things down to keep from overheating. In any case, running at full capacity will likely cause things to burn out in a year or less.
_unix.36282
When I program I like to swap these keys:Esc TabCtrl CapsLockIn ~/.xmodmap, I have specified these re-mappings:keycode 66 = Control_Lkeycode 37 = Caps_Lockkeycode 23 = Escapekeycode 9 = TabThe Escape and Tab keys swaps, no problem, but instead of Caps_Lock and Control_L swapping, both those keys becomes Caps_Lock.Whatever I try to do, the Control keys doesn't get assigned to Caps_Lock (keycode 66). If I leave the keycode 66 =, the key is un-assigned, but when I assign Control_L or Control_R, it just doesn't work. But, if I assign some other key, for example, keycode 66 = Tab, it gets assigned, no problem.Its like xmodmap just doesn't want Caps Lock and Control keys to be swapped. Really frustrating. Any help/pointers would be really helpful.P.S: I am using Archlinux.
Remapping Caps Lock with xmodmap doesn't work
keyboard;xmodmap
The xmodmap(1) man page has an example for exactly this ! ! Swap Caps_Lock and Control_L ! remove Lock = Caps_Lock remove Control = Control_L keysym Control_L = Caps_Lock keysym Caps_Lock = Control_L add Lock = Caps_Lock add Control = Control_Lbut if you want to finish doing it the way you started, I think you need to add at least the remove and add lines remove Lock = Caps_Lock remove Control = Control_L keycode 37 = Caps_Lock keycode 66 = Control_L add Lock = Caps_Lock add Control = Control_LI'm guessing that's the case based on this paragraph add MODIFIERNAME = KEYSYMNAME ... This adds all keys containing the given keysyms to the indi cated modifier map. The keysym names are evaluated after all input expressions are read to make it easy to write expressions to swap keys (see the EXAMPLES section).which makes it sound like modifier changes (shift, control, etc.) don't get applied until you run that too.(And logically the same with remove)
_webmaster.29170
I am an IB(International Baccalaureate) student, and for preparing for my ITGS(Information Technologies in Global Societies) exam, and I would like to ask few questions to people who has worked with web-based booking systems.Here are the questions;*Could you please describe the booking system you are using ?*If so, how did you build your interactive booking system ?(Java, Flash, Javascript)*If you are using Flash for your interactive booking system, how did you manage the problem with smart phones and tablet devices that doesnt support flash? *What can you say when you compare the cost of building your booking system and the other alternatives ?*What difficulties you went through when you made your system ?*What are the advantages of using such a system ? Why did you prefer to do so ?*ls your system multilingual ? If not, why ?*If so, what are the difficulties of having a multi-lingual web-site? How did you solve these problems ?These are the questions I sent to some companies, who never replied back, so you may find them a little bit weirdAny help will doThanks
web based booking systems
web services
null
_softwareengineering.131055
I'm about to write a simple script to test a dataset for certain conditions. I was designing it as a set of functions each one describing the condition to be tested and pass them to the test engine:# The tester engine:all(f(dataset) for f in conditions)I realized that my approach was similar to unit testing. So, to avoid repeating myself, I am thinking of using my favorite unit testing framework instead.What do you think about that idea?Have any of you used an unit test framework for any other purpose than test code?
Is it a good idea to use an unit test framework for another purpose than test code?
unit testing
null
_unix.26461
Maybe it's a bit strange - and maybe there are other tools to do this but, well..I am using the following classic bash command to find all files which contain some string:find . -type f | xargs grep somethingI have a great number of files, on multiple depths. first occurrence of something is enough for me, but find continues searching, and takes a long time to complete the rest of the files. What I would like to do is something like a feedback from grep back to find so that find could stop searching for more files. Is such a thing possible?
bash find xargs grep only single occurence
bash;find;grep;xargs
Simply keep it within the realm of find:find . -type f -exec grep something {} \; -quitThis is how it works:The -exec will work when the -type f will be true. And because grep returns 0 (success/true) when the -exec grep something has a match, the -quit will be triggered.
_unix.366703
ubuntu 16.04, dnsmasq 2.75NOTE: I have dnsmasq running with --hostsdir option so dnsmasq should pick up host entries written to that directory.Steps to reproduce:... fresh machine boot ...$> echo 'MY-IP test.domain.com' > $DNSMASQ_HOSTS_DIR/test$> sudo ip netns add test$> sudo ip link add veth-test type veth peer name test-eth0$> sudo ip link set test-eth0 netns test$> sudo ip addr add 10.0.4.1/24 dev veth-test$> sudo ip link set veth-test up$> sudo ip netns exec test ip addr add 10.0.4.2/24 dev test-eth0$> sudo ip netns exec test ip link set test-eth0 up$> sudo ip netns exec test ip link set lo up$> sudo ip netns exec test ip route add default via 10.0.4.1$> sudo ip route add 10.0.4.2/32 via default dev veth-test$> sudo mkdir -p /etc/netns/test$> sudo bash -c cat > /etc/netns/test/resolv.conf << EOL nameserver MY_IP EOL$> sudo ip netns exec test bashtest-ns$> host test.domain.com ;; connection timed out; no servers could be reachedSo, I've created the network namespace but cannot access my dns server. The following 2 steps fix the problem and result in my confusion.... return to the default global namespace ...$> sudo service dnsmasq restart$> sudo ip netns exec test bashtest-ns~# host test.domain.com test.domain.com has address MY_IP ... WORKS! WHAT?!To my understanding, restarting dnsmasq should not have an effect on the networking of my network namespace. Before the restart I cannot reach the dns server, after the restart (and a new instance of the network namespace shell) I am able to access and get answers from dnsmasq. I cannot understand why dns is not working without the dnsmasq restart, and why it does work afterwards (although I have a feeling they are related :=]).Any help would be greatly appreciated.
dnsmasq not available from network namespace at first
ubuntu;dnsmasq;network namespaces
null
_unix.346073
There are some unstable/risky ways such as the thread How to Get A with Dots in Dvorak of Ubuntu 16.04? to get the feature but I cannot run it in many environments. Germans need their owns (a/e/u/o with dots) as shown here, while nordic (Finland, Sweden, Norway, Denmark, ...) people need similar keys (a/o with dots). I think one-level keyboard approach is better than two-level keyboard approach. OptionsTo get such a keyboard layout by default in Debian would be great. To get a package in apt for such a keyboard would be good.Maybe an other way ...Doing those changes manually like in the first thread is not an option because of the risks in different environments.OS X International Dvorak has such a feature by default, which can be used as a benchmark, but also the manual approach as done in the first thread answer. There is a ticket open in Chromium development for such a feature in the thread International Dvorak with Deadkeys targeted in Chromebook.Testing clearkimura's answer in DebianOutputmasi@masi:~/Downloads$ sudo cp dvorak_intl /usr/share/X11/xkb/symbols/dvorak_intlmasi@masi:~/Downloads$ setxkbmap -verbose dvorak_intlmasi@masi:~/Downloads$ setxkbmap -I ~/.xkb dvorak_intl -print | xkbcomp -I$HOME/.xkb - $DISPLAYWarning: Type ONE_LEVEL has 1 levels, but <RALT> has 2 symbols Ignoring extra symbolsWarning: Key <OUTP> not found in evdev+aliases(qwerty) keycodes Symbols ignoredWarning: Key <KITG> not found in evdev+aliases(qwerty) keycodes Symbols ignoredWarning: Key <KIDN> not found in evdev+aliases(qwerty) keycodes Symbols ignoredWarning: Key <KIUP> not found in evdev+aliases(qwerty) keycodes Symbols ignoredWarning: Key <RO> not found in evdev+aliases(qwerty) keycodes Symbols ignoredWarning: Key <I192> not found in evdev+aliases(qwerty) keycodes Symbols ignoredWarning: Key <I193> not found in evdev+aliases(qwerty) keycodes Symbols ignoredWarning: Key <I194> not found in evdev+aliases(qwerty) keycodes Symbols ignoredWarning: Key <I195> not found in evdev+aliases(qwerty) keycodes Symbols ignoredWarning: Key <I196> not found in evdev+aliases(qwerty) keycodes Symbols ignoredWarning: Key <I255> not found in evdev+aliases(qwerty) keycodes Symbols ignoredWarning: No symbols defined for <AB11> (keycode 97)Warning: No symbols defined for <JPCM> (keycode 103)Warning: No symbols defined for <I120> (keycode 120)Warning: No symbols defined for <AE13> (keycode 132)Warning: No symbols defined for <I149> (keycode 149)Warning: No symbols defined for <I154> (keycode 154)Warning: No symbols defined for <I168> (keycode 168)Warning: No symbols defined for <I178> (keycode 178)Warning: No symbols defined for <I183> (keycode 183)Warning: No symbols defined for <I184> (keycode 184)Warning: No symbols defined for <FK19> (keycode 197)Warning: No symbols defined for <FK24> (keycode 202)Warning: No symbols defined for <I217> (keycode 217)Warning: No symbols defined for <I219> (keycode 219)Warning: No symbols defined for <I221> (keycode 221)Warning: No symbols defined for <I222> (keycode 222)Warning: No symbols defined for <I230> (keycode 230)Warning: No symbols defined for <I247> (keycode 247)Warning: No symbols defined for <I248> (keycode 248)Warning: No symbols defined for <I249> (keycode 249)Warning: No symbols defined for <I250> (keycode 250)Warning: No symbols defined for <I251> (keycode 251)Warning: No symbols defined for <I252> (keycode 252)Warning: No symbols defined for <I253> (keycode 253)RestartOutput: the keyboard layout is not active anymoreGo to Region & Language > choose > search Dvorak > Choose Dvorak with dead keys in Fig. 1Output: the expected keyboard layout now active and selectable in the top barIn Regien & Language, put your primary keyboard layout at the top in Fig. 2 i.e. remove your previous keyboard layouts at the top. This way, you can put Dvorak international with dead keys as your primary keyboard which stays there also after restart. Fig. 1 Region & Language settings after the change, Fig. 2 Region & Language settings when Dvorak international with dead keys as the primary keyboard layoutOS: Debian 8.7Hardware: Asus Zenbook UX303UB, HP 2002 laptopWindow manager: Gnome 3.14
How to get stable International Dvorak with first-level deadkeys in Debian?
debian;keyboard layout;x server;dvorak
null
_cogsci.271
Whenever I start a new research project, I typically have to find questions and scales that have proven validity in measuring constructs of interest (e.g., psychological / political science / social science scales). This can often be quite time consuming, and often there are issues of cost and copyright to consider.QuestionsWhat are general tips for efficiently and cost effectively locating measures for a given construct?Are there any databases that make it easy to locate such measures?Is there anything like a StackOverflow/PatternLibrary/Best Practices compendium of measures or advice on locating measures?
How to efficiently locate existing psychology and social science measures?
measurement;reproducible research;test;reference request
null
_unix.336431
I'm a web developer and I know a lot about servers and scripting languages, but I don't know much about Bash and Linux(in comparison).It's my understanding that it is possible to allow login to a computer when a user attaches a usb key. I was unfortunately not able to make this work on my machine, and I began to wonder if it would still be possible for someone to bypass my password(based on this article)I have some very lucrative programs that I want to keep away from prying eyes and I want to know if there is any way to somehow perform a DDoS attack on my machine if a specific usb is not inserted. I don't want the user to be able to do anything at all on my laptop. If anyone has some suggestions. I would be greatly appreciative.
USB encryption login Ubuntu Elementary OS Freya
security;usb drive;elementary os;screen lock;disk encryption
null
_cogsci.13194
Does the neural activity that correlates with motor skill function tend to be focused near or far from the outer surface of the brain, or both? And what about perception?My deeper curiosity being: I'd conjecture that the first is either near the surface or both, given the ability of technology now to read input directly from the brain in order to move virtual objects.
Where is motor skill function located within the brain?
perception;neuroanatomy;motor;brain computer interface
null
_cstheory.27481
For the purposes of this question, a cut in a graph $G$ is the edge-set $\delta (S)\subseteq E(G)$ between some vertex-set $S$ and its complement. A max cut is one with at least as many edges as any other cut. Finding a max cut is NP-hard, but a greedy algorithm (e.g.) can approximate a max cut, finding a cut with at least half as many edges as possible.Equivalently, a cut $\delta (S)\subseteq E(G)$ is a max cut if and only if$$| \delta (S)\cap \delta (T) |\geq \frac{1}{2}|\delta (T)| \qquad \forall\text{ cuts } \delta (T)\subseteq E(G).$$(Sidenote: It should be clear that the standard definition implies this one. To show that these inequalities imply $\delta (S)$ is at least as big as any other cut $\delta (S')$, observe that $$|\delta (S)| - |\delta (S')| = |\delta (S) \cap \delta (S\Delta S')| - |\delta (S') \cap \delta (S\Delta S')|.$$ Because the two edge-sets appearing in the right-hand side partition the edges of the cut $\delta (S\Delta S')$, applying the above inequality with $S\Delta S'$ in the role of $T$ gives $|\delta (S)|-|\delta (S')|\geq 0$.)I'd like to know whether max cuts can be easily approximated in the sense of my second definition. Specifically:Question: Is there a polynomial-time algorithm to find a cut $\delta (S)\subseteq E(G)$ with $$| \delta (S)\cap \delta (T) |\geq \epsilon |\delta (T)| \qquad \forall\text{ cuts } \delta (T)\subseteq E(G)$$ for some $\epsilon > 0$?
Approximating a max-cut's intersection with other cuts
graph theory;co.combinatorics;approximation algorithms;max cut
null
_unix.353956
I have a FreeBSD 9.3 installation inside the 192.168.2.x LAN2 which is connected to the 192.168.1.x LAN1 (router WAN IP is 192.168.1.10).This BSD runs SSH and FTP services. I can use both services from any LAN2 computer. But I am unable to connect from LAN1.I don't think the problem is in router settings because I have HTTP and FTP servers on another LAN2 machines, and all of them are accessible from LAN1 computers without problems.All needed ports are forwarded in the router. I can connect to another LAN2 servers using 192.168.1.10:port (even from LAN2).I saw several threads describing similar problems (usually with SSH server) and tried all solutions I could find, but none of them worked for me.These are relevant lines from /etc/rc.conf:ifconfig_em0=inet 192.168.2.8 netmask 255.255.255.0defaultrouter=192.168.2.1sshd_enable=YESftpd_enable=YESftpd_flags=-D -lUpdateWhen I run Putty SSH to 192.168.1.10:20022 (forwarded to 192.168.2.8:22) from LAN1 pc, it shows Network error: Connection timed out message. FTP connection from Total Commander shows : Connect call failed!. Doing the same thing from LAN2 shows FTP home directory and BSD login prompt.Command-line FTP from LAN1 to 192.168.1.10:20021 shows ftp: connect: unknown error number. Doing the same thing for accessible FTP (another port) shows : 220 messages (welcome and auth). I can telnet other FTP and HTTP.cat /var/log/auth.log | grep sshd shows basically two kind of messages:Server listening on 0.0.0.0 port 22 / :: port 22Accepted / closed connection from 192.168.2.6 (another LAN2 pc)LAN1 addresses are not mentioned by sshd.This is what I get while connected by SSH from another LAN2 pc:root@bsdpc:/ # ifconfigem0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500 options=9b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM> ether 08:00:27:11:97:cf inet 192.168.2.8 netmask 0xffffff00 broadcast 192.168.2.255 inet6 fe80::a00:27ff:fe11:97cf%em0 prefixlen 64 scopeid 0x1 nd6 options=29<PERFORMNUD,IFDISABLED,AUTO_LINKLOCAL> media: Ethernet autoselect (1000baseT <full-duplex>) status: activelo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> metric 0 mtu 16384 options=600003<RXCSUM,TXCSUM,RXCSUM_IPV6,TXCSUM_IPV6> inet6 ::1 prefixlen 128 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x3 inet 127.0.0.1 netmask 0xff000000 nd6 options=21<PERFORMNUD,AUTO_LINKLOCAL>root@bsdpc:/ # sockstatUSER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESSlpvoid sshd 1398 3 tcp4 192.168.2.8:22 192.168.2.6:1186lpvoid sshd 1398 4 stream -> ??root sshd 1395 3 tcp4 192.168.2.8:22 192.168.2.6:1186root sshd 1395 5 stream -> ??root ftpd 567 3 dgram -> /var/run/logprivroot ftpd 567 5 tcp6 *:21 *:*root ftpd 567 6 tcp4 *:21 *:*smmsp sendmail 537 3 dgram -> /var/run/logroot sendmail 534 3 tcp4 127.0.0.1:25 *:*root sendmail 534 4 dgram -> /var/run/logprivroot sshd 531 3 tcp6 *:22 *:*root sshd 531 4 tcp4 *:22 *:*root syslogd 400 4 dgram /var/run/logroot syslogd 400 5 dgram /var/run/logprivroot syslogd 400 6 udp6 *:514 *:*root syslogd 400 7 udp4 *:514 *:*root devd 310 4 stream /var/run/devd.pipe
Cannot connect to FreeBSD server behind a router
freebsd;port forwarding;internet;connectivity
null
_cstheory.6684
From time to time, I have to read a paper with unclear typesetting. By this, I mean:very small fonts; sometimes 8pt or smaller.very bad scan;Using bitmap fonts instead of vector ones.too old formatting (usually dating back to 1970s or the beginning of 1980s.)In these cases, one might prefer to read a more clear version submitted to the authors' home page. Unfortunately, the author version is not always available; and even in that case, they might be very lengthy (the so-called full version of the paper).In the case of bitmap fonts, I found a good strategy: Find the postscript (PS) version of the paper, and convert the bitmap fonts to their vector counterparts using pkfix or a combination of pkfix-helper + pkfix, whichever applies (read the documentation).However, I still can't find a workaround for other problems. Specially, small-font papers bother me a lot. My best bet is to use a desk lamp: I don't know why, but magically the words seem larger under its light!How do you read a paper whose typesetting is unclear? Specially, what do you do when the font is too small to read?PS: Some months ago, I found an application which splited a PDF into several segments, so that they were easy to read on an iPhone or the like. (Sorry, I don't recall the name of that app.) However, the output was downgraded to fit the iPhone small screen, and therefore it wasn't apt for computer screen or printer.
Reading Papers with Unclear Typesetting
soft question;advice request
null
_codereview.53768
I have developed a generic HTTP functionality using Android Asynctask and Apache HTTP client. Please review the code and let me know if it is the right way of doing or there are other ways to achieve it.Async classpublic class HTTPAsyncTask extends AsyncTask<String, Void, String> { private CallBack mCb; HashMap<String, String> mData = null; List<NameValuePair> mParams= new ArrayList<NameValuePair>(); String mTypeOfRequest; String mStrToBeAppended = ; boolean isPostDataInJSONFormat = false; JSONObject mJSONPostData = null; public HTTPAsyncTask(CallBack c, HashMap<String, String> data, JSONObject jsonObj, String request) { mCb = c; mTypeOfRequest = request; mJSONPostData = jsonObj; if((data != null) && (jsonObj == null)){ mData = data; if(mTypeOfRequest.equalsIgnoreCase(GET)){ Iterator<String> it = mData.keySet().iterator(); while(it.hasNext()){ String key = it.next(); mParams.add(new BasicNameValuePair(key, mData.get(key))); } for (int i = 0; i<mParams.size()-1; i++){ mStrToBeAppended+= ? + mParams.get(i).getName() + = + mParams.get(i).getValue() + &; } //add the last parameter without the & mStrToBeAppended+= ? + mParams.get(mParams.size()-1).getName() + = + mParams.get(mParams.size()-1).getValue(); } if(mTypeOfRequest.equalsIgnoreCase(POST)){ Iterator<String> it = mData.keySet().iterator(); while(it.hasNext()){ String key = it.next(); mParams.add(new BasicNameValuePair(key, mData.get(key))); } } } if ((mData == null) && (jsonObj != null)){ isPostDataInJSONFormat = true; } } @Override protected String doInBackground(String... baseUrls) { publishProgress(null); if(mTypeOfRequest.equalsIgnoreCase(GET)){ String finalURL = baseUrls[0]+ mStrToBeAppended; return HttpUtility.GET(finalURL); } if (mTypeOfRequest.equalsIgnoreCase(POST)){ if(isPostDataInJSONFormat == false){ return HttpUtility.POST(baseUrls[0],mParams ); } else { return HttpUtility.POST(baseUrls[0], mJSONPostData); } } return null; } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(String result) { mCb.onResult(result); } @Override protected void onProgressUpdate(Void...voids ) { mCb.onProgress(); }}HTTPUtility Classpublic class HttpUtility { public static String GET(String url){ InputStream inputStream = null; String result = ; try { // create HttpClient HttpClient httpclient = new DefaultHttpClient(); // make GET request to the given URL HttpResponse httpResponse = httpclient.execute(new HttpGet(url)); // receive response as inputStream inputStream = httpResponse.getEntity().getContent(); // convert inputstream to string if(inputStream != null){ result = convertInputStreamToString(inputStream); //inputStream.close(); } else result = Did not work!; } catch (Exception e) { Log.d(InputStream, e.getLocalizedMessage()); } return result; } public static String POST(String url, List<NameValuePair> mParams){ InputStream inputStream = null; String result = ; try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(mParams, UTF-8)); HttpResponse httpResponse = httpclient.execute(post); // receive response as inputStream inputStream = httpResponse.getEntity().getContent(); // convert inputstream to string if(inputStream != null){ result = convertInputStreamToString(inputStream); //inputStream.close(); } else result = Did not work!; } catch (Exception e) { Log.d(InputStream, e.getLocalizedMessage()); } return result; } public static String POST(String url, JSONObject obj){ InputStream inputStream = null; String result = ; HttpClient httpclient = new DefaultHttpClient(); try{ HttpPost post = new HttpPost(url); post.setHeader(Content-type, application/json); StringEntity se = new StringEntity(obj.toString()); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, application/json)); post.setEntity(se); HttpResponse httpResponse = httpclient.execute(post); // receive response as inputStream inputStream = httpResponse.getEntity().getContent(); // convert inputstream to string if(inputStream != null){ result = convertInputStreamToString(inputStream); } else result = Did not work!; } catch (Exception e) { Log.d(InputStream, e.getLocalizedMessage()); } return result; } public static String convertInputStreamToString(InputStream inputStream) throws IOException{ BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); String line = ; String result = ; while((line = bufferedReader.readLine()) != null) result += line; inputStream.close(); return result; }}Callback interfacepublic interface CallBack { public void onProgress(); public void onResult(String result); public void onCancel();}Main activity classInside the activity class final CallBack c = new CallBack(){ @Override public void onProgress() { // TODO Auto-generated method stub mProgressDialog.show(); } @Override public void onResult(String result) { // TODO Auto-generated method stub mProgressDialog.dismiss(); mStrResult = result; Toast.makeText(getApplicationContext(), mStrResult, Toast.LENGTH_SHORT).show(); } @Override public void onCancel() { // TODO Auto-generated method stub }};And then the Asynctask is called inside the Activity like the following://For JSON PostdataString url= Your URLJSONObject postData = new JSONObject();postData.put(Key1, Data1);postData.put(Key2, Data2);HTTPAsyncTask asyncTask = new AsyncTask(mContext,mCallback, null, postData, POST);asyncTask.execute(url);//For Get dataString url = Your URL;HashMap getData = new HashMap<Object, Object>();getData.put(Key,Data);getData.put(Key,Data));mGetGCMMessageAsyncTask = new HTTPAsyncTask(mContext, mCallback, getData, null, GET);mGetGCMMessageAsyncTask.execute(url);
Generic HTTP using Android Asynctask
java;android;asynchronous;http
I'll go over quickly with the minors generals things : You should remove TODO Auto-generated method stub when you implemented the method.You should always put a modifier for your class variable.Don't use the implementation of a class, use the interface Map instead of HashMapI don't like the mVariableName notation. (this is subjective)An HTTP Get and Post are very two different things, don't try to mix them up in the same method. It feels to me like you're HTTPAsyncTask should be separated with one abstract class that encapsulate the common code and two implementation with HTTPAsyncTaskGet and HTTPAsyncTaskPost. This would remove one argument to the constructor, better represent the differences between get/post and would help remove duplicate code. You will need to modifiy the implementation of doInBackground but this should simple and will help this method shine with simplicty by removing the if(mTypeOfRequest.equalsIgnoreCase(POST)) conditions. This would be your basic constructor :public HTTPAsyncTask(CallBack c, HashMap<String, String> data, JSONObject jsonObj) { mCb = c; mTypeOfRequest = request; mJSONPostData = jsonObj; mData = data; if ((mData == null) && (jsonObj != null)){ isPostDataInJSONFormat = true; }}And with your other class you would have : public HTTPAsyncTaskGet(CallBack c, HashMap<String, String> data, JSONObject jsonObj) { super(c,data,jsonObj); if((data != null) && (jsonObj == null)){ Iterator<String> it = mData.keySet().iterator(); while(it.hasNext()){ String key = it.next(); mParams.add(new BasicNameValuePair(key, mData.get(key))); } for (int i = 0; i<mParams.size()-1; i++){ mStrToBeAppended+= ? + mParams.get(i).getName() + = + mParams.get(i).getValue() + &; } //add the last parameter without the & mStrToBeAppended+= ? + mParams.get(mParams.size()-1).getName() + = + mParams.get(mParams.size()-1).getValue(); } }}The high number of arguments for a method is something that must point you to something smelly. It's hard to have high readability when you have a tons of arguments. There is one case where you need data != null and one case jsonObj != null. You should then redefines your constructor to take one or the other, not both. Yes you will probably have more line of codes, but it will be readable. Every constructor will look unique and will have less complexity if you remove those if. Exemple :public HTTPAsyncTaskGet(CallBack c, JSONObject jsonObj) { super(c,null,jsonObj);}You should not recreate a new DefaultHttpClient(); for every request. You should always try to use the same client. This will help for performance concern and will reduce the complexity of encountering bugs for various reasons (too much connections open, etc). try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(mParams, UTF-8)); HttpResponse httpResponse = httpclient.execute(post); // receive response as inputStream inputStream = httpResponse.getEntity().getContent(); // convert inputstream to string if(inputStream != null){ result = convertInputStreamToString(inputStream); //inputStream.close(); } else result = Did not work!; } catch (Exception e) { Log.d(InputStream, e.getLocalizedMessage()); }This is very prone to errors. You need to always consume the content of the entity, even in case of failure, or your connection won't close and you'll run into problems. Always make sure that you consume your entity. You can use EntityUtils.consume(HttpEntity).
_unix.265927
I'm making a php panel from which you can install apps like owncloud & plex on your server. I've created multiple bash scripts that install and remove software. I tested all of them from shell, everything works as it should. However, when I run the scripts from php as root using sudo on ubuntu 15.10, apt-get & dpkg are not working as they should.In visudo I have:seedbox ALL = (root) NOPASSWD: /bin/appinstallerappinstaller is a bash script that run the install/uninstall apps bash scripts (e.g. appinstaller plex)Plex script example:dpkg --configure -acd /tmpwget https://downloads.plex.tv/plex-media-server/0.9.15.6.1714-7be11e1/plexmediaserver_0.9.15.6.1714-7be11e1_amd64.debdpkg -i plexmediaserver_0.9.15.6.1714-7be11e1_amd64.debWhen I run appinstaller directly from bash everything works perfectly.When I run appinstaller from php using (confirmed that script is running as root):exec(sudo /bin/appinstaller plex > /home/installer.log 2>&1 &);It works but I get apt & dpkg errors when I try to install other apps such as:E: The package plexmediaserver needs to be reinstalled, but I can't find an archive for it. (even though it's installed and working)And also dpkg --configure -a returns an error.Plex is working fine, but seems like apt doesn't finish the installation process and gets stuck somewhere, also commands running after the apt-get install/dpkg won't run from php but will run from bash. I tried to run the script also from cron & systemctl and I get the same issue.It's worth noting that some apps are installing/uninstalling without any issues.What could be making the difference between running the script from php/cron/systemctl or from shell directly? Can I emulate normal bash session?
Issue with bash script running from php as root
bash;shell script;apt;dpkg
null
_cs.44625
Given a set of (propositional) formulae $\Phi$, two formulae $\phi$ and $\xi$, determine whether there exists $\Psi\subseteq \Phi$ such that $\Psi\models \phi$ and $\Psi\not\models \xi$. Question: what is the (theoretical) complexity of this problem? Is it in DP?
Complexity of a SAT related problem
complexity theory;satisfiability;propositional logic
null
_unix.173894
I use Thunderbid, Enigmail, GnuPG and pinentry.When I receive encrypted message, how I can determine which algorithm is used:for encryptionfor checksuming (SHA1 or not)for compression
How to learn encryption type from a mail message?
gpg;thunderbird;pgp
I don't know of a method inside thunderbird, but storing the message as a file and dropping to the shell will reveal the information you're looking for.Getting verbosegpg -vv will output very verbose information on the input, including the information you're looking for.An ExampleAn example of the output can be generated by encrypting and signing a message to your own key:echo 'foo' | gpg --recipient a4ff2279 --encrypt --sign | gpg -vvThe slightly stripped output (removing bulky parts not relevant to the question at all) looks like::pubkey enc packet: version 3, algo 1, keyid CC73B287A4388025 data: [4095 bits][snip, gpg asking for passphrase]gpg: public key encrypted data: good DEK:encrypted data packet: length: unknown mdc_method: 2gpg: encrypted with 4096-bit RSA key, ID A4388025, created 2014-03-26 Jens Erat (born 1988-01-19 in Stuttgart, Germany)gpg: AES256 encrypted data:compressed packet: algo=2:onepass_sig packet: keyid 8E78E44DFB1B55E9 version 3, sigclass 0x00, digest 8, pubkey 1, last=1:literal data packet: mode b (62), created 1418376556, name=, raw data: 4 bytesgpg: original file name=''foo:signature packet: algo 1, keyid 8E78E44DFB1B55E9 version 4, created 1418376556, md5len 0, sigclass 0x00 digest algo 8, begin of digest 81 67 hashed subpkt 2 len 4 (sig created 2014-12-12) subpkt 16 len 8 (issuer key ID 8E78E44DFB1B55E9) data: [4095 bits]gpg: Signature made Fri Dec 12 10:29:16 2014 CET using RSA key ID FB1B55E9gpg: using subkey FB1B55E9 instead of primary key A4FF2279[snip, trust validation]gpg: binary signature, digest algorithm SHA256gpg: decryption okayInterpreting the OutputIf GnuPG only prints algorithm IDs (like for the compression), these can be looked up in RFC 4880, Section Constants. Specifically for this example, we will find use of following algorithms:AES256 for symmetric encryptionMDC 2 means SHA1 for the Modification Detection Code, which is the only defined at this timeCompression algorithm 2, resolving to ZLIBSHA256 for the signature
_codereview.14257
I have a program that displays colorful shapes to the user. It is designed so that it is easy to add new shapes, and add new kinds of views.Currently, I have only two shapes, and a single text-based view. In the near future, I'm going to implement a Triangle shape and a BezierCurve shape. I'm also going to implement these views:GraphicalView - uses a graphics library to render shapes on screen.OscilloscopeView - draws the shapes on an oscilloscope.DioramaView - a sophisticated AI directs robotic arms to construct the scene using construction paper, string, and a shoebox.The MVC pattern is essential here, because otherwise I'd have a big intermixed tangle of oscilloscope and AI and Graphics library code. I want to keep these things as separate as possible.#model codeclass Shape: def __init__(self, color, x, y): self.color = color self.x = x self.y = yclass Circle(Shape): def __init__(self, color, x, y, radius): Shape.__init__(self, color, x, y) self.radius = radiusclass Rectangle(Shape): def __init__(self, color, x, y, width, height): Shape.__init__(self, color, x, y) self.width = width self.height = heightclass Model: def __init__(self): self.shapes = [] def addShape(self, shape): self.shapes.append(shape)#end of model code#view codeclass TickerTapeView: def __init__(self, model): self.model = model def render(self): for shape in self.model.shapes: if isinstance(shape, Circle): self.showCircle(shape) if isinstance(shape, Rectangle): self.showRectangle(shape) def showCircle(self, circle): print There is a {0} circle with radius {1} at ({2}, {3}).format(circle.color, circle.radius, circle.x, circle.y) def showRectangle(self, rectangle): print There is a {0} rectangle with width {1} and height {2} at ({3}, {4}).format(rectangle.color, rectangle.width, rectangle.height, rectangle.x, rectangle.y)#end of view code#set upmodel = Model()view = TickerTapeView(model)model.addShape(Circle (red, 4, 8, 15))model.addShape(Circle (orange, 16, 23, 42))model.addShape(Circle (yellow, 1, 1, 2))model.addShape(Rectangle(blue, 3, 5, 8, 13))model.addShape(Rectangle(indigo, 21, 34, 55, 89))model.addShape(Rectangle(violet, 144, 233, 377, 610))view.render()I'm very concerned about the render method of TickerTapeView. In my experience, whenever you see code with a bunch of isinstance calls in a big if-elseif block, it signals that the author should have used polymorphism. But in this case, defining a Shape.renderToTickerTape method is forbidden, since I have resolved to keep the implementation details of the view separate from the model.render is also smelly because it will grow without limit as I add new shapes. If I have 1000 shapes, it will be 2000 lines long.Is it appropriate to use isinstance in this way? Is there a better solution that doesn't violate model-view separation and doesn't require 2000-line if blocks?
Displaying colorful shapes to the user
python;mvc
null
_unix.192753
I have some Python files that I wrote on my Windows PC and then sent over to a Linux machine using pscp. They work as intended on Windows, but when I try to execute them on the Linux machine, I always get an error message. I use the following process to run the code after importing the file test.py:First, I add the shebang line at the top of test.py:#!/usr/bin/python# rest of codeThen I modify permissions and try to run the script:chmod +x test.py./test.pywhich gives me the error message./test.py: Command not found.If I create a file from scratch on the Linux machine and type in the exact same program text, the program will run just fine. Also, if I type the following code, the program runs just fine:python test.pyCan anyone explain what is happening here? Thanks.
Why won't my python scripts run without the python command when moved from Windows to Linux?
command line;python;executable;shebang
null
_cogsci.17177
Are there any frameworks to evaluate the quality of a theoretic concept in cognitive science (ideally with references)?For social sciences I found the following:Gerring, J. (1999). What makes a concept good? A criterial framework for understanding concept formation in the social sciences. Polity, 31(3), 357-393.
What Makes a Concept Good in Cognitive Science?
cognitive psychology
null
_codereview.94290
I have just installed Ubuntu and am re-familiarizing myself with Python. I learned the basics in late 2012-early 2013 and I'm practicing with it in order to get better at programming concepts and practice.'''Snake Gameimplements gameplay of classic snakegame with TkinterAuthor: Tracy Lynn Wesley'''import threadingimport randomimport os.pathfrom Tkinter import *WIDTH = 500HEIGHT = 500class Snake(Frame): def __init__(self): Frame.__init__(self) #Set up the main window frame as a grid self.master.title(Snake *** Try to beat the high score! ***) self.grid() #Set up main frame for game as a grid frame1 = Frame(self) frame1.grid() #Add a canvas to frame1 as self.canvas member self.canvas = Canvas(frame1, width = WIDTH, height = HEIGHT, bg =white) self.canvas.grid(columnspan = 3) self.canvas.focus_set() self.canvas.bind(<Button-1>, self.create) self.canvas.bind(<Key>, self.create) #Create a New Game button newGame = Button(frame1, text = New Game, command = self.new_game) newGame.grid(row = 1, column = 0, sticky = E) #Create a label to show user his/her score self.score_label = Label(frame1) self.score_label.grid(row = 1, column = 1) self.high_score_label = Label(frame1) self.high_score_label.grid(row = 1, column = 2) #Direction label (for debugging purpose) #self.direction_label = Label(frame1, text = Direction) #self.direction_label.grid(row = 1, column = 2) self.new_game() def new_game(self): self.canvas.delete(ALL) self.canvas.create_text(WIDTH/2,HEIGHT/2-50,text=Welcome to Snake!\ + \nPress arrow keys or click in the window\ + to start moving!, tag=welcome_text) rectWidth = WIDTH/25 #Initialize snake to 3 rectangles rect1 = self.canvas.create_rectangle(WIDTH/2-rectWidth/2, HEIGHT/2-rectWidth/2, WIDTH/2+rectWidth/2\ , HEIGHT/2+rectWidth/2, outline=#dbf, fill=#dbf\ , tag=rect1) rect2 = self.canvas.create_rectangle(WIDTH/2-rectWidth/2, HEIGHT/2-rectWidth/2, WIDTH/2+rectWidth/2\ , HEIGHT/2+rectWidth/2, outline=#dbf, fill=#dbf\ , tag=rect2) rect3 = self.canvas.create_rectangle(WIDTH/2-rectWidth/2, HEIGHT/2-rectWidth/2, WIDTH/2+rectWidth/2\ , HEIGHT/2+rectWidth/2, outline=#dbf, fill=#dbf\ , tag=rect3) #initialize variables that contribute to smooth gameplay below: # #set rectangle width and height variables for use with new rectangles on the canvas self.rectWidth = rectWidth #lastDirection recorded because first 2 rectangles always overlap while moving, #but if user goes right then immediately left the snake should run into itself and #therefore end the game (See below functions self.check_collide and self.end_game) self.lastDirection = None self.direction = None #Used to force snake to expand out on first move self.started = False #Used to force game loop to halt when a collision occurs/snake out of bounds self.game_over = False #Initialize game score to 0 self.score = 0 #Initialize high score from file if (os.path.isfile(high_score.txt)): scoreFile = open(high_score.txt) self.high_score = int(scoreFile.read()) scoreFile.close() else: self.high_score = 0 self.high_score_label[text] = High Score: + str(self.high_score) self.rectangles = [rect1,rect2,rect3] #Initialize the dot (which the snake eats) self.dot = None #Start thread for snake to move when direction is set self.move() def create(self, event): self.lastDirection = self.direction if self.game_over == False: if event.keycode == 111: self.direction = up elif event.keycode == 114: self.direction = right elif event.keycode == 116: self.direction = down elif event.keycode == 113: self.direction = left elif event.x < WIDTH/2 and HEIGHT/3 < event.y < HEIGHT-HEIGHT/3: self.direction = left #(Debug) #self.direction_label[text] = LEFT elif event.x > WIDTH/2 and HEIGHT/3 < event.y < HEIGHT-HEIGHT/3: self.direction= right #(Debug) #self.direction_label[text] = RIGHT elif WIDTH/3 < event.x < WIDTH-WIDTH/3 and event.y < HEIGHT/2: self.direction = up #(Debug) #self.direction_label[text] = UP elif WIDTH/3 < event.x < WIDTH-WIDTH/3 and event.y > HEIGHT/2: self.direction= down #(Debug) #self.direction_label[text] = DOWN def first_movement(self): w = self.rectWidth self.canvas.delete(welcome_text) #Expand snake in direction chosen if self.direction == left: self.canvas.move(rect1,-w,0) self.canvas.after(100) self.canvas.move(rect1,-w,0) self.canvas.move(rect2,-w,0) elif self.direction == down: self.canvas.move(rect1,0,w) self.canvas.after(100) self.canvas.move(rect1,0,w) self.canvas.move(rect2,0,w) elif self.direction == right: self.canvas.move(rect1,w,0) self.canvas.after(100) self.canvas.move(rect1,w,0) self.canvas.move(rect2,w,0) elif self.direction == up: self.canvas.move(rect1,0,-w) self.canvas.after(100) self.canvas.move(rect1,0,-w) self.canvas.move(rect2,0,-w) self.canvas.after(100) def _move(self): w = self.rectWidth while True: self.score_label[text] = Score: + str(self.score) if self.started == False and self.direction != None: self.first_movement() self.started = True elif self.started == True and self.game_over == False: if self.dot == None: self.make_new_dot() lock = threading.Lock() lock.acquire() endRect = self.rectangles.pop() frontCoords = self.canvas.coords(self.rectangles[0]) endCoords = self.canvas.coords(endRect) #(Below for Debugging) #print self.direction #print Front: + str(frontCoords) + Back: + str(endCoords) if self.direction == left: self.canvas.move(self.canvas.gettags(endRect), int(frontCoords[0]-endCoords[0])-w,\ int(frontCoords[1]-endCoords[1])) elif self.direction == down: self.canvas.move(self.canvas.gettags(endRect), int(frontCoords[0]-endCoords[0]),\ int(frontCoords[1]-endCoords[1])+w) elif self.direction == right: self.canvas.move(self.canvas.gettags(endRect), int(frontCoords[0]-endCoords[0])+w,\ int(frontCoords[1]-endCoords[1])) elif self.direction == up: self.canvas.move(self.canvas.gettags(endRect), int(frontCoords[0]-endCoords[0]),\ int(frontCoords[1]-endCoords[1])-w) self.canvas.after(100) self.rectangles.insert(0, endRect) lock.release() self.check_bounds() self.check_collide() elif self.game_over == True: break; def move(self): threading.Thread(target=self._move).start() def make_new_dot(self): if self.dot != None: self.canvas.delete(self.dot) self.dot = None dotX = random.random()*(WIDTH-self.rectWidth*2) + self.rectWidth dotY = random.random()*(HEIGHT-self.rectWidth*2) + self.rectWidth self.dot = self.canvas.create_rectangle(dotX,dotY,dotX+self.rectWidth,dotY+self.rectWidth\ ,outline=#ddd, fill=#ddd, tag=dot) def grow(self): w = self.rectWidth lock = threading.Lock() lock.acquire() #Increase the score any time the snake grows self.score += 100 endCoords = self.canvas.coords(self.rectangles[len(self.rectangles)-1]) #(Debug) #print endCoords: + str(endCoords) thisTag = rect + str(len(self.rectangles) + 1) x1 = int(endCoords[0]) y1 = int(endCoords[1]) x2 = int(endCoords[2]) y2 = int(endCoords[3]) if self.direction == left: x1 += w x2 += w elif self.direction == right: x1 -= w x2 -= w elif self.direction == down: y1 -= w y2 -= w elif self.direction == up: y1 += w y2 += w #(Debug) #print self.direction #print new coords: + str(x1) + , + str(y1) + , + str(x2) + , + str(y2) thisRect = self.canvas.create_rectangle(x1, y1, x2, y2, outline=#dbf,\ fill=#dbf, tag=thisTag) #print str(self.rectangles) self.rectangles.append(thisRect) #print str(self.rectangles) lock.release() def check_bounds(self): coordinates = self.canvas.coords(self.rectangles[0]) if len(coordinates) > 0: if coordinates[0] < 0 or coordinates[1] < 0 or coordinates[2] > WIDTH\ or coordinates[3] > HEIGHT: self.end_game() def check_collide(self): frontCoords = self.canvas.coords(self.rectangles[0]) #(For Debugging) #for rect in self.rectangles: #coords = self.canvas.coords(rect) #print Front: + str(frontCoords) + coords: + str(coords) #Check to see if the snake's head(front) is overlapping anything and handle it below overlapping = self.canvas.find_overlapping(frontCoords[0],frontCoords[1]\ ,frontCoords[2],frontCoords[3]) for item in overlapping: if item == self.dot: #Snake collided with dot, grow snake and move dot self.grow() self.make_new_dot() if item in self.rectangles[3:]: #Snake has collided with its body, end game self.end_game() #Snake tried to move backwards (therefore crashing into itself) if (self.lastDirection == left and self.direction == right) or\ (self.lastDirection == right and self.direction == left) or\ (self.lastDirection == up and self.direction == down) or\ (self.lastDirection == down and self.direction == up): self.end_game() def end_game(self): self.game_over = True self.canvas.create_text(WIDTH/2,HEIGHT/2,text=GAME OVER!) if self.score > self.high_score: scoreFile = open(high_score.txt, w) scoreFile.write(str(self.score)) scoreFile.close() self.canvas.create_text(WIDTH/2,HEIGHT/2+20,text=\ You beat the high score!) #(Debug) #self.direction_label[text] = ENDEDSnake().mainloop()
Classic Snake game using Python, Tkinter, and threading
python;beginner;game;multithreading;tkinter
If you haven't read it already I'd highly recommend that you check out PEP8 as it is a great starting point for a lot of questions about Python code conventions. Some of what I write here will be repeated there.Tightly coupled functionsOne issue with your design is that your functions are designed such that you must call them in a particular sequence in order to get the results you want.init calls new_game calls move which creates the game loop thread in _move. While this might be somewhat appropriate in this case it is usually indicative of bad design. Generally speaking the more you can make your functions not depend on side-effects the better as it allows you more effective code reuse opportunities. Additionally if a precondition for a function is that another function must be called you really need to document that clearly, as this could be a large source of confusion (and hence bugs) for other people (including the future you) who read/maintain the codebase in the future.Commented out codeUse your version control software to manage your changes in code instead of commenting out code. If you are not using version control then you should strongly consider learning how as this is one of the most valuable productivity boosters you can get with development.If you want logging perhaps look into the standard library logging module.DocumentationYou have used comments fairly extensively in the code here which definitely helps when reading it. Also I noticed you put a docstring for the module which is good to see! Putting some docstrings in the rest of your code will help other people read it as it gives you a standardized place to look for documentation on different functions/classes/methods.For example:def new_game(self): Creates a new game. Sets up canvas and 1initial game conditions.Prefer named constants over multiple variablesmagic variables are often less clear than explicit named variables.if event.keycode == 111: self.direction = upWhen I'm reading this code I have to guess from the context that the 111 is the keycode for the up key. I have to read ahead and look at the context to figure this out.The code is much more clear if you give a named variable:UP_KEY_CODE = 111if event.keycode == UP_KEY_CODE:I notice a similar situation with the directions, create a variable for the various different directions instead of hardcoding strings everywhere. For example in a lot of places in the code you have lines such as:if self.direction == left:Personally I'd prefer to define something such as LEFT_DIRECTION = left then compare like so:if self.direction == LEFT_DIRECTION:This makes means if you change the type of value stored in self.direction in the future it's very easy to make changes. Currently you would have to track down all the different strings and change them. Having used other languages I think this is a very good example of where an enumeration type is useful but others might consider that somewhat un-pythonic, so do whatever you think is most readable.Going further I'd consider making some sort dictionary to store the keycode along with the associated action that needs to be done if you start getting more keyboard keys being used in your program. I'll explain this in more depth if you make a follow up question.Checking for non-empty sequencesThe pythonic way to do this is explained in PEP8.instead of:if len(coordinates) > 0:if self.dot != None:elif self.game_over == True:do:if coordinates:if self.dot:elif self.game_over:This makes your code shorter and improves readability.duplicated codeAny time you see code that does essentially the same thing you should consider re-writing it. Python is highly amenable to the don't-repeat-yourself idea so keep that in mind. if self.direction == left: self.canvas.move(rect1,-w,0) self.canvas.after(100) self.canvas.move(rect1,-w,0) self.canvas.move(rect2,-w,0) elif self.direction == down: self.canvas.move(rect1,0,w) self.canvas.after(100) self.canvas.move(rect1,0,w) self.canvas.move(rect2,0,w) elif self.direction == right: self.canvas.move(rect1,w,0) self.canvas.after(100) self.canvas.move(rect1,w,0) self.canvas.move(rect2,w,0) elif self.direction == up: self.canvas.move(rect1,0,-w) self.canvas.after(100) self.canvas.move(rect1,0,-w) self.canvas.move(rect2,0,-w)First of all I'd clean up the indentation here to be consistent, but once we have done that we see that all of this is essentially doing the same thing. I would therefore break this into a function:def expand_snake(self, x_direction, y_direction): Expand the snake in the given directions as per the parameters. self.canvas.move(rect1, x_direction, y_direction) self.canvas.after(100) self.canvas.move(rect1, x_direction, y_direction) self.canvas.move(rect2, x_direction, y_direction)Then the code just becomes:if self.direction == left: self.expand_snake(-w, 0):elif self.direction == down: self.expand_snake(0, w):elif self.direction == right: self.expand_snake(w, 0):elif self.direction == up: self.expand_snake(0 -w):Less duplication and less chances for something to go wrong. Additionally as mentioned before you probably want to make named constants for the directions or use an enumeration instead of strings such as up down etc for keeping track of the directions.
_unix.132406
I've got a question about gpg and signing a key automatically via bash:I've got a script, that is doing the beginning of signing:gpg --recv $schluessel1gpg --edit $schluessel1If I try something like this:lsignit is ignored and just show me the below output. gpg>From the above prompt, I can write manually lsign and later y in.Is it possible to do these two steps automatically?
sign and trust gpg key automatically via bash
bash;gpg
null
_webapps.109046
With Facebook, if you go to for example a company's page and post something on their wall, or even another friend's page, how do you stop it from notifying all your friends of what you posted?I don't care if they visit the actual company's/other friend's page and see it, but I don't want all my friends being notified of what I posted.Is there a way to do this? I can't see anything in Facebook's privacy settings.
How do you stop your friends from being notified of what you post on others' walls?
facebook;facebook pages;facebook privacy
If you are frequent poster (means if you keep updating status, sharing etc), they will not get any notification but if you are posting something after a long time (3 weeks or more), they will get notifcation. There is no control.If you are writting something on your friend's wall, only they can control who can see that. You can't do anything in that, it will be visible to all your friends.If you are writting something on any Page, it will be public.There is no privacy setting to control this.
_codereview.144912
I am working on an application which responds to different screen resolutions. At a certain minimum DPI, we want to apply a set of styles. We also want to apply that same set of styles if the class hidpi is present on the root html element. Our project uses LESS.This is the code I inherited. I've replaced the styles with some placeholders for the sake of this question (so don't mind the colors):@media all and (min-resolution: 96dpi) { .foo { color: maize; } .bar { color: blue; }}html.hidpi { .foo { color: maize; } .bar { color: blue; }}Attempt at reducing duplicationAs you can see, the code between the media query and html.hidpi is exactly the same, so I figured I should be able to reduce duplication. I came up with a solution using a mixin:.mixinHidpi() { .foo { color: maize; } .bar { color: blue; }}@media all and (min-resolution: 96dpi) { .mixinHidpi();}html.hidpi { .mixinHidpi();}Can any more be done to reduce duplication? Are there any problems with the way I'm doing things now? In particular, I've only ever seen very simple examples of using mixins, so I'm not sure if I'm using them in the way they are supposed to be used.
Applying a set of styles both with a media query and with nested rules
less css
null
_webapps.69344
I've got a large Tumblr archive and would like to tweet one post every few days to Twitter. Is there any way of doing this automatically?
Is it possible to automatically schedule old Tumblr posts to appear on Twitter?
twitter;tumblr;automation
null
_cs.32191
I know that it is decidable problem to check whether given context free grammar represents empty language -- for instance, AFAIR one could convert it to Chomsky normal form, and then check if any word of length $\leq 2^n$ (or maybe $\leq 2^{n+1}$, I'm not sure) belongs to the language, where $n$ is IIRC the number of nonterminals in CNF. If not, then no longer words belong either and the grammar is empty.The above algorithm has the unpleasant property of having exponential complexity. The questions that interest me are:Is there a polynomial algorithm to check whether given CFG represents empty language?What's the (asymptotically) best known algorithm for that?What's the simplest polynomial algorithm for that (not necessarily having best known complexity)?
complexity of determining whether a language given by context free grammar is empty
complexity theory;formal languages;context free
null
_webmaster.44219
I have just been marking them as fixed, but they just keep coming back and I don't want to have to keep coming back to mark as fixed. Google is showing about 150 of my pages as 404's but they all register as 200 all good when I do a header check.Is there another reason these may show up as 404's?
Google Webmasters showing 404's but header check showing 200 All Good
google search console;404
null
_unix.255702
I tried this command:[silas@mars 11]$ string=xyababcdabababefab[silas@mars 11]$ echo ${string/abab/\n}xy\ncdabababefab[silas@mars 11]$I also tried to replace \n to '\n' and to \n . I can't use AWK or sed (this is a part from a homework exercise, and the teacher don't allow to use in this specific exercise).
Replace a string in a string with a new line (\n) in Bash
bash;string
You should use -e with echo as follows:echo -e ${string/abab/'\n'}From manpage:-e enable interpretation of backslash escapesIf -e is in effect, the following sequences are recognized:\\ backslash\a alert (BEL)\b backspace\c produce no further output\e escape\f form feed\n new line\r carriage return\t horizontal tab\v vertical tab
_softwareengineering.300155
I am building a security mechanism and I need a Pseudorandom functionality in my app. More particularly I need to convert a String to fix length.My strings are random already, they just to long so I want to convert them to fix size. A trivial solution(the one that I am using now) will be just cut the extra characters, the problem with this approach that it reduce from the strength of my original random that I used to generate the string at the first place.So I need some sort of method that will except an array of bytes and will give me new array of bytes, but it will be always the same output for given input.And I dont want to use solutions like XOR or some other math, I want it to be psado random, and I will store the psado random key or data in local storage.Any suggestions?
Pseudorandom in Android
algorithms;android;random
null
_webapps.21697
I just clicked on a link that was an article posted on slashdot in 2003. It discusses Python vs Perl and it was quite interesting to read the comments from that time. How can I find the oldest articles posted on Slashdot?
How to find the oldest article on Slashdot?
search;slashdot
It seems that Slashdot articles have the article ID in the URL, which is incremented with each article, so just taking any article, and putting 1 where is the article id in the URL will reveal the oldest one.This one might be it: http://slashdot.org/story/1/There is some discussion about the very topic there, and there seems to be some error.Then it seems there is a tag for the first post on Slashdot:http://slashdot.org/tag/firstpostWhich links to an article from December 31 1997:http://slashdot.org/story/98/01/01/012000/become-007-on-the-internet
_softwareengineering.238478
At the office we just got a new colleague who is visually impaired. I'm in charge of organizing the planning poker sessions and the new colleague must participate as a member of the team. We have these nice sets of poker cards with planning poker numbers on them, but that doesn't help of course for our new colleague.Until now we fixed this problem by just naming the estimates, letting the new colleague say their estimate right after the rest had put down their card, then the rest flips their card and I name the estimates in a row.My question(s): Is there any one who has experience with this kind of situation and have a better solution? Is there such a thing as Braille poker cards?The current solution does work, but I think this can be improved for us all by for example Braille poker cards.
Planning poker with visually impaired colleague
agile;scrum;planning;project planning
You can solve this problem with a free and simple solution.In our team, if we ever forget our planning poker cards we instead use our hands i.e. We clench our fists and show our estimates all at the same time. We find that this approach works very well as usually our estimates are on average at most eight points and any 13 point estimates are followed by a longer than usual discussion anyway.I think this method would work great for you and your visually impaired colleague, as he/she would be able to give their estimate at exactly the same time as their team mates. When you all show your hands you then can go around the table and each member can speak out loud the estimate they gave. Yes, it won't be ideal if your team regularly estimates above 13 points, but I think it'll work great if your team usually estimates below this level.
_unix.375116
I restored an Arch Linux system from a BTRFS snapshot. All is well except that journald has to be restarted after every boot:systemctl restart systemd-journaldIf I don't do this, journalctl shows old output that ends with the last shutdown before the reboot.Also, when checking the status of systemd units, I see messages similar to this: Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.I'm not even sure how to troubleshoot this. Suggestions?
systemd-journald not starting after boot up
arch linux;systemd;systemd journald
null
_unix.80225
Is there a way to customize the debian installer to be part of a custom debian distro, also is it possible to make the distro contain certain files such as pdfs, videos, etc. as part of the installation.
Custom installation for a custom Debian Distro?
debian;system installation
null
_unix.111584
My plan is to use vpxenc (video encoder) and flac (audio encoder) to record the screen/microphone, but I'm stopped short of entering the input (file) in the command line.How can I exactly address a screen from a terminal?
How exactly is a Linux desktop/device/display expressed in a terminal?
terminal;video;display;recording
null
_unix.328677
I wanted to know if it is possible to change kernels, for example, replacing Fedora's Linux kernel to that of FreeBSD's.Now, there already existed the Debian GNU/kFreeBSD. Is it possible for me to customize a Linux distro to contain a BSD kernel?
Is it possible to change the kernel in a UNIX/Linux system?
linux;fedora;kernel;linux kernel;gnu
null
_unix.145464
I've written a simple init script to start and stop a Python script as a service. I have to be explicit about the version of Python I'm running, because this is on a CentOS 5 box with Python 2.4 & 2.6 installed (both via yum).Here's what I have so far:#!/bin/sh# chkconfig: 123456 90 10workdir=/usr/local/bin/Foostart() { cd $workdir /usr/bin/python26 $workdir/Bar.py & echo FooBar started.}stop() { pid=`ps -ef | grep '[p]ython26 /usr/local/bin/Foo/Bar.py' | awk '{ print $2 }'` echo $pid kill $pid sleep 2 echo FooBar stopped.}case $1 in start) start ;; stop) stop ;; restart) stop start ;; *) echo Usage: /etc/init.d/foobar {start|stop|restart} exit 1esacexit 0Two things I need help with:1) I want to be smarter about the filename and directory name management, and set some variables up to so that anything repeated later in the script (like workdir). My main problem is the grep statement, and I haven't figured out how to deal with the variables inside the grep. I'd love any suggestions of a more efficient way to do this.2) I want to add status support to this init script and have it check to see if the Bar.py is running.
Grepping a variable
shell;python;ps;init script
I may be missing something but I don't understand why you are fiddling with grep in the first place. That's what pgrep is for:#!/bin/sh# chkconfig: 123456 90 10workdir=/usr/local/bin/Foostart() { cd $workdir /usr/bin/python26 $workdir/Bar.py & echo FooBar started.}stop() { pid=`pgrep -f '/Bar.py$'` echo $pid kill $pid sleep 2 echo FooBar stopped.}case $1 in start) start ;; stop) stop ;; restart) stop start ;; *) echo Usage: /etc/init.d/foobar {start|stop|restart} exit 1esacexit 0The pgrep command is designed to return the PIDs of processes whose name matches the pattern given. Since this is a python script, the actual process is something like:python /usr/local/bin/Bar.pyWhere the process name is python. So, we need to use pgrep's -f flag to match the entire name: -f, --full The pattern is normally only matched against the process name. When -f is set, the full command line is used.To ensure that this does not match things like fooBar.py, the pattern is /Bar.py$ so that it matches only the portion after the last / and at the end of the string ($).For future reference, you should never use ps | grep to get a PID. That will always return at least two lines, one for the running process and one for the grep you just launched:$ ps -ef | grep 'Bar.py'terdon 27209 2006 19 17:05 pts/9 00:00:00 python /usr/local/bin/Bar.pyterdon 27254 1377 0 17:05 pts/6 00:00:00 grep --color Bar.py
_datascience.14434
I am not sure how to formulate this problem clearly into a machine learning task yet. So hope you guys can chime in and give me some help.Problem : To predict whether someone will pick up their phone during office hours in week n+2 by looking at customer's behaviour in week n. Data : I have calling records for about 3 months, which is aggregated on customer level. The various attributes include, num of calls, duration of calls, time of calls, amount of data traffic. But of course, these main attributes are further split into at about 20 attributes.Current Approach (Very Manual) : I look at data at week n+2 and get the group of guys who picked up the phone during office hours (duration of calls > 5s and time of call). This is the target group, T.I look at data at week n and manually try all possible combinations of the attributes to get as close to T as possible. But trying manually seems tiring after some time. The baseline is of course using the same conditions as at week n+2. But the whole idea will be to increase this number.Question : Is there any way I can transform this dataset so that I would be able to do accomplish it as a machine learning task ?
Period Predictive Model
predictive modeling
null
_softwareengineering.277587
I have clients, each of whom have an app with a bunch of users.Their user data could be pretty different, but there is also a lot of overlap. Ex: all their users have gender and age and plenty of other things, so it makes sense to have a standard user_table schema across all clients (with a column for each attribute).But there is also user information specific to each client. Ex. one might have relationship_status for their users, which other clients do not have. While another has height for their users, which other clients do not have.How to I design a schema that is appropriate for both of these cases at once?One possibility is to somehow have a different schema for each client, but this seems like it could be unnecessary hassle. Another possibility is to put every column in the standard schema across all clients, but then the columns that are unique to a single client would just sit empty for all the other clients.
SQL - for some attributes specific to different clients' users, how to handle schema?
sql;coding standards;schema;postgres
null
_datascience.10481
This question is more about inference and decision making based on statistical data, so I hope I'm in the right place. If not, let me know if I should migrate this question elsewhere.I have a data set specifying the predicted shoe size of different people for various shoe models, and also the manually measured correct shoe size. For instance person #1 was predicted to have a shoe size of 8 for shoe model A, and the actual size she wears is 8.5. Each record includes the person, shoe model, predicted size and actual size. I already calculated the delta between these two values for each record, then summarized the average offset and standard deviation for all shoe models. Here's an example of the offset data (n is the sample size from the average offset and standard deviation was calculated for each model):+-------+----------------+-----+----+| model | Average Offset | SD | n |+-------+----------------+-----+----+| 1 | 0.4 | 1.0 | 16 || 2 | -0.8 | 0.8 | 5 || 3 | 0.8 | 0.7 | 10 || 4 | 0.5 | 0.9 | 12 || 5 | 0.7 | 0.8 | 6 || 6 | 0.1 | 0.9 | 28 || 7 | 0.5 | 0.8 | 16 || 8 | 0.1 | 0.7 | 18 || 9 | 0.3 | 0.5 | 6 || 10 | 2.7 | 0.3 | 5 || 11 | -0.2 | 0.6 | 33 || 12 | 1.0 | 0.5 | 6 || 13 | 0.0 | 0.0 | 5 || 14 | -0.1 | 0.6 | 13 || 15 | 0.0 | 0.4 | 4 || 16 | -0.9 | 0.5 | 7 || 17 | 0.2 | 0.8 | 9 || 18 | -0.2 | 0.8 | 20 || 19 | -1.1 | 0.7 | 9 || 20 | -0.1 | 0.6 | 14 || 21 | -1.1 | 0.8 | 55 || 22 | -1.2 | 0.8 | 12 || 23 | -0.3 | 0.5 | 12 || 24 | -0.1 | 0.4 | 10 || 25 | 0.6 | 0.9 | 29 |+-------+----------------+-----+----+And as a chart:If you're wondering why analyze this per shoe model at all, then the answer is that we know from shop experience that different shoe models have particular structures and materials that have of consistent effect on shoe size preference.Now to my actual question:My goal is to plug average offsets back into the prediction calculation to adjust it based on previously recorded offsets.The question is - when does it make sense to use an offset value, and when that value is unusable.I tend to disregard average offsets where the SD is close to the size of the average, but mathematically, plugging in such an average to adjust all predictions for this model is likely to do more good than harm. Or does it?What would be a good approach to decide which of these averages is useful?Suggestion for additional insights or analysis techniques are welcome.
Adjusting predicted values based on average offsets from past predictions
statistics;predictive modeling;descriptive statistics
null
_unix.350731
I created a serial port in VirtualBox that maps to the host socket device: /tmp/xxx. But I haven't managed to find the way to use this file for anything. I can't ssh to it, so what tool can I use to interact with it?ls -la shows it is a socket link
Connect to serial port of VirtualBox guest via host socket
virtualbox;serial port;socket
If the serial port mapped to the socket file on the host provides a serial console, you can connect to it using a control and terminal emulation program such as minicom or GTKTerm.In minicom you can specify the socket file as the device to connect using the --device|-D command line option, or in the minicom configuration file, for example:$minicom -D unix\#/tmp/xxxIn GTKTerm the same can be achieved by modifying the Port under Configuration > Port menu.
_softwareengineering.263977
A project that I am working on has the following code for interfaceexample:using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Test{ public interface IDeviceEssentials { string Model { get; set; } string Manufacturer { get; set; } string BIOSVersion { get; set; } string TotalPhysicalMemory { get; set; } string TotalVirtualmemory { get; set; } string OSName { get; set; } }}every other class implementing this interface uses Automatic properties which renders the getters and setters useless so the effective implementation is reduced tousing System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Test{ public interface IDeviceEssentials { string Model; string Manufacturer; string BIOSVersion; string TotalPhysicalMemory; string TotalVirtualmemory; string OSName; }}For which simply a structure or class is enough to hold the data..The main usage of interface is polymorphism making use of liskov substitution, even though the above code is using the getter setter it is effectively reduced to variable decleration by all the classes implementing it (by using automatic property). That is there is no need i want to mock the above interface. even if it is designed as a class I can simply mock by creating new class of it.Question are :-I think the above properties are providing data representation only. is it ok to use interface only for data representation?
if a c# interface contain only getter and setter definition, is it a code smell?
c#;object oriented;code quality
No it isn't a code smell in itself. Having many implementations using only auto properties is a code smell - this is where you refactor common code into a base class and define it as virtual so that the extending class can override it where necessary.every other class implementing this interface uses Automatic properties which renders the getters and setters uselessNo, automatic properties do not render the interface definition useless. Your two illustrated interfaces are not the same - in fact the second one is illegal as you cannot define a field in an interface. Automatic properties still use getters and setters (they're inserted by the compiler), so using automatic properties satisfies the requirements of the interface. Simply declaring the field public string Model; in your implementation does not satisfy the interface.You'll see from the following image that even though I used automatic properties in the implementation there are still getters and setters implemented for me:If that still makes no sense, think of it this way: the interface defines a contract. If I later refactor my implementation so that I don't use auto properties then the interface guarantees that I expose both a getter and setter. Consuming code uses my implementation via its interface, not directly accessing the concrete implementation. This means I can refactor the implementation and the caller doesn't have to change at all.
_cogsci.1316
I have experienced this phenomenon several times and checked with other people as well.It goes like this: you hear something, but it's just a sound with no meaning. Some seconds later, you consciously remember the sound and make sense out of it (like a word or a phrase that somebody tells).Although both processes (remembrance and understanding) are fairly common, I find it weird that understanding is not automatically triggered when processing a sound and it can be demanded on purposeIs there any name for this phenomenon? (Would appreciate some detail on it too.)
Hearing first but understanding later?
terminology;memory;perception
The phenomena broadly makes sense in terms of information processing models of memory and cognition.The phonological loopFor example, you could think about the phenomena in terms of a phonological loop. To Quote the Wikipedia article on Baddeley's model of working memoryThe phonological loop (or articulatory loop) as a whole deals with sound or phonological information. It consists of two parts: a short-term phonological store with auditory memory traces that are subject to rapid decay and an articulatory rehearsal component (sometimes called the articulatory loop) that can revive the memory traces.Any auditory verbal information is assumed to enter automatically into the phonological store. Visually presented language can be transformed into phonological code by silent articulation and thereby be encoded into the phonological store. This transformation is facilitated by the articulatory control process. The phonological store acts as an 'inner ear', remembering speech sounds in their temporal order, whilst the articulatory process acts as an 'inner voice' and repeats the series of words (or other speech elements) on a loop to prevent them from decaying. The phonological loop may play a key role in the acquisition of vocabulary, particularly in the early childhood years.[3] It may also be vital for learning a second language.Applying this to the phenomenaIn the very short term (perhaps a few seconds), you presumably have a internal representation of the raw sound, which might if you were to attend to it afterwards be then processed into words and meaning.Alternatively, you may hear the words but not process the meaning. Presumably these words can remain represented for a little longer in your short term memory than can the raw sounds (as a very rough guess, perhaps up to 10 or 20 seconds). And then you can return to the words and process them.Another possibility is that you have basically processed the meaning of the original words, but were perhaps immediately distracted, and then a little later you remembered what was said and that you need to respond.
_opensource.5328
My project about to launch to public. So I'm preparing open source credit notice page. Since my project is developed in JavaScript, there's lots of node_modules in the development directory.Here's question. Could I reference the packages only if I directly deepened in my package.json? My project referenced only 25 packages in package.json but there's 300+ packages in my node_modules/ directory.Some packages like gulp-* is referenced as devDependencies and clearly not included in the final dist of my project. So I think I could omit credit for these packages.I'm not sure about indirect referenced packages. Let say package A depends on package B and my project depends on only A. In this case my dist contains both A and B. Could I omit credit for package B?
Should I credit indirect depended package in my open source credit notice too?
license notice;dependencies;npm
You added this important comment:it's frontend project. So packages are bundled and minimized then redistributed to end user.So the answer to:Should I credit indirect depended package in my open source credit notice too?... is a clear YES.Since you are redistributing your code with directs deps, and with deps of deps, and with deps of deps of deps and ...... you have to comply with the license requirements of all the packages A.I explained in this other answer some of the specifics of dealing with package dependencies:You need to know:The whole chain of program or package dependenciesThe purpose and use of each program or package in that chain (test, tool, runtime)Which dependent are shipped and redistributed with your product, application or library vs. which may be installed by your userThe license of each dependency in this chainAnything that would not be redistributed (e.g. devDependencies in the case of npms) does not have to be included. If there is any code using some copyleft license you may have also source code redistribution requirements. And depending on the licenses and the way you integrate with these copyleft-licensed packages this requirement may extend to the tools used for minification and to possibly your own source code or other packages in the dependencies tree.
_codereview.139061
I'm doing this assignment were they have told me to sort an array of objects with name and age. What do you think about my solution?Edited to take in consideration comments, Thanks for the feedback guys!var familyAgesPropName = [ { name: Raul, age: 27 }, { name: Jose, age: 55 }, { name: Maria, age: 52 }, { name: Jesus, age: 18 }, { name: Neo, age: 2 }];var familyAgesWithoutPropName = [ { Raul: 27 }, { Jose: 55 }, { Maria: 52 }, { Jesus: 18 }, { Neo: 2 }];var familyAgesWithoutPropNameMissingAge = [ { Raul: 27 }, { Jose: 55 }, { Maria: '' }, { Jesus: 18 }, { Neo: 2 }];var familyAgesWithoutPropNameMissingName = [ { Raul: 27 }, { Jose: 55 }, { 52: }, { Jesus: 18 }, { Neo: 2 }];var familyAgesWithoutPropNameMissingNameAndNULL = [ null, { Raul: 27 }, { Jose: 55 }, { 52: }, { Jesus: 18 }, { Neo: 2 }];/** @brief: cleaningAndFormatting is a function that takes the input array (that I assume can come in any way) and converts it to a proper format that is correct for using and outputing it. The format of my choice is [{name: String, age: Int}, item2, ...] @param: array with the data. @notes: If the input array comes already in the desired format we can comment this function improving the performance of the process If the name is actually a number (only digits) then we put it infront to see that we have a problem with it If the age is empty or a string that doesn't make sense we assign 0 to put it after the problmatics**/// var cleaningAndFormatting = (function(array) {// for (var i = array.length - 1; i >= 0; i--) {// if (array[i].name === undefined) {// var tempObject = {};// for (var key in array[i]) {// tempObject.name = key;// tempObject.age = parseInt(array[i][key]) || 0;// if (!isNaN(tempObject.name)) {// tempObject.age = -1;// }// if (isNaN(tempObject.age)) {// tempObject.age = 0;// }// }// array[i] = tempObject;// }// }// });function cleanRow(element, index, array) { if (element == null) { delete array[index]; return; } if (element.name == undefined) { element.name = Object.keys(element)[0]; } if (element.age == undefined) { element.age = element[element.name]; element.age = parseInt(element.age) || 0; } if (!isNaN(element.name)) { element.age = -1; } delete element[element.name];}familyAgesPropName.forEach(cleanRow);console.log(familyAgesPropName);console.log(familyAgesPropName);familyAgesWithoutPropName.forEach(cleanRow);console.log(familyAgesWithoutPropName);console.log(familyAgesWithoutPropName);familyAgesWithoutPropNameMissingAge.forEach(cleanRow);console.log(familyAgesWithoutPropNameMissingAge);console.log(familyAgesWithoutPropNameMissingAge);familyAgesWithoutPropNameMissingName.forEach(cleanRow);console.log(familyAgesWithoutPropNameMissingName);console.log(familyAgesWithoutPropNameMissingName);familyAgesWithoutPropNameMissingNameAndNULL.forEach(cleanRow);console.log(familyAgesWithoutPropNameMissingNameAndNULL);console.log(familyAgesWithoutPropNameMissingNameAndNULL);/** @brief: Manual implementation of the quicksort algorithm adapted our desired array, I've chosen do the algorithm manually because the sorting in JavaScript is very dependant on the implementation of the engine that runs the JavaScript making it erratic and not desirable to use. For example chrome V8 engine for JavaScript unstable.**/var quickSort = (function() { function partition(array, left, right) { var cmp = array[right - 1].age, minEnd = left, maxEnd; for (maxEnd = left; maxEnd < right - 1; maxEnd += 1) { if (array[maxEnd].age <= cmp) { swap(array, maxEnd, minEnd); minEnd += 1; } } swap(array, minEnd, right - 1); return minEnd; } function swap(array, i, j) { var temp = array[i]; array[i] = array[j]; array[j] = temp; return array; } function quickSort(array, left, right) { if (left < right) { var p = partition(array, left, right); quickSort(array, left, p); quickSort(array, p + 1, right); } return array; } return function(array) { return quickSort(array, 0, array.length); };}());quickSort(familyAgesPropName);quickSort(familyAgesWithoutPropName);quickSort(familyAgesWithoutPropNameMissingAge);quickSort(familyAgesWithoutPropNameMissingName);
Sort an array of name and ages in JavaScript
javascript;array;sorting
Based on your implementation, I have no other choice than to say welcome to JavaScript . I will point out few observationscleaningAndFormatting():null is a valid value for an object in javascript. For instance replacing one of the object with a null e.g var familyAgesPropName3 = [ null, {name: Jose, age: 55}, {name: Maria, age: 52}, {name: Jesus, age: 18}, {name: Neo, age: 2}];will generate this errorTypeConverting Comparison (==): converts the operands to the same type before making the comparison. So undefined== null will return true as opposed to false. In Javascript, we use the strict comparison (e.g., ===) to return only true if the operands are of the same type and the contents match. You can readmore from this page Comparison OperatorsJavascript provides ForEach function which can replace the nested for..loop . I will give you a pseudocode on how to start function houseKeeping(element, index, array) { if (element.name == undefined) { element.name = element.age; // other implementations } // other implementations }To use the ForEach /* Calling the foreach*/familyAgesPropName.forEach(houseKeeping);for( var key in array[i]){..} is inefficient as the loop is performed twice; key in the first iteration is name and second key. You should see your error now . tempObject.name = key; is assigned itself and after the key-Horrendous ImplementationI'm not sure of what you are trying to achieve with this line if (!isNaN(tempObject.name)) {...}.An excerpt from isNan() explains how NaN values are generated:NaN values are generated when arithmetic operations result in undefined or unrepresentable values. Such values do not necessarily represent overflow conditions. A NaN also results from attempted coercion to numeric values of non-numeric values for which no primitive numeric value is available.There was no arithmetic operation conducted on tempObject.name except tempObject.age, I doubt if that line is necessary. It would be nice if you could explain what you mean by this and I will update my answer if necessaryIf the name is actually a number (only digits) then we put it infront to see that we have a problem with itconsole.log(array);: I believe you want to return the modified array rather than printing to the console . You can replace that with return array;tempObject: you don't need to create an extra variable when you could just modify the array itselfquickSort()I just looked at your quicksort briefly. Although I will be back to give further reviews , I will leave you with a note here for nowDestructing Assignment : I'm not sure how conversant you are with this type of assignment in javascript. This will save you some coding lines meaning you don't have to have a swap function what you could do is replaceswap(array, minEnd, right - 1);// replace witharray[minEnd, right - 1] = array [right - 1,minEnd]I will back later in the day. I hope this helps.
_unix.33617
I've just set up a new machine with Ubuntu Oneiric 11.10 and then runapt-get updateapt-get upgradeapt-get install gitNow if I run git --version it tells me I have git version 1.7.5.4 but on my local machine I have the much newer git version 1.7.9.2I know I can install from source to get the newest version, but I thought that it was a good idea to use the package manager as much as possible to keep everything standardized.So is it possible to use apt-get to get a newer version of git, and what is the right way to do it?
How can I update to a newer version of Git using apt-get?
ubuntu;apt;upgrade;git
You have several options:Either wait until the version you need is present in the repository you use.Compile your own version and create a deb.Find a repository that provides the version you need for your version of your distribution(e.g. Git PPA).If you don't need any particular feature from the newer version, stay with the old one.If a newer version is available in the repositories you use, then apt-get update && apt-get upgrade (as root) updates to the latest available version.
_webmaster.26821
I'm running multiple feeds of loops on my homepage much like youtube.com and I want to use AJAX to load them instead of tabbed content with jQuery. Since most of my traffic comes from posts I'd like to know how it impacts my site with Google with less crawlable links and excerpts.My question is this: How bad is it for my SEO to use AJAX to load the feeds on my homepage? Each feed contains links to new posts in different categories and I have 10 of them so loading them with jQuery Tabs adds load time but makes it all crawlable.
Using AJAX on homepage to handle feeds, bad for SEO?
seo;ajax;homepage
Isn't the AJAX simply loading html into your page? So it's not like the search engines won't recognize the content.Having dynamic content on your home page isn't new or bad. As you pointed out youtube.com as well as Digg.com are constantly updating their content and plenty of other sites for that matter.It's actually good to have fresh content on your home page they'll recognize the page as being updated recently and begin crawling it more. That may or may not affect your rankings but they should crawl it more often with fresh content.
_softwareengineering.157039
After a system has gone through many migrations, and evolved enough for a second version, does it make sense to keep the old migrations around? I mean, old versions will use them to upgrade to the new one, sure, but should a fresh install have its database go through all the historical changes before arriving at the current shape? My gut feeling is that a fresh install should create the database as it is, not go through every mistake that was made in the product lifecycle until reaching a stable condition.I've recently asked a question on SO about splitting a django app into multiple ones. Problem is: after I've done that I'll never be able to remove the old app, since the other ones' past migrations still refer to it, and would break without it, even if the current version of my project does not use it anymore. OTOH if I rewrote the history in a major update I could pretend that the broken app never existed in the first place, which I believe would make the code cleaner (past revisions would still exist in version control though).The above scenario is just an example, but I'm interested in arguments about the general case: have fresh installs create the database as it is, or go through every migration ever done in the product lifecycle?
Keeping historical migrations in Django-south
database;django;migration
Yes, it's a good idea to clean up migration history. Having numerous migrations is really error prone. So it's good idea to make the current state of your servers into the new initial migration.
_codereview.14330
If I have an array:var names = ['John', 'Jim', 'Joe'];and I want to create a new array from names which afterwards will look like:newNames = ['John John', 'Jim Jim', 'Joe Joe']What I came up with is the following:var newNames = [];var arr = null;var loop = 0;$.each(names, function (i, item) { arr = []; loop = 2; while (loop--) { arr.push(item); } newNames.push(arr.join(' '));});Seems like there should be a shorter, easier way to do this. As you can see we can repeat the names with a space n times. I'm experimenting with different ideas/concepts, having fun.
Javascript Array processing
javascript;jquery
Create a function that operates on values in the manner you want...function dupe(n) { return n + + n }then use Array.prototype.map...var newNames = names.map(dupe)or jQuery's not quite compliant version, $.map...var newNames = $.map(names, dupe)You can also create a function factory that will make a dupe function that will add the operate on the value a given number of times.function dupeFactory(i) { return function(n) { var j = i-1 , m = n while (j--) m += + n return m }}Then use it like this...var newNames = names.map(dupeFactory(3))Or make reuse of the functions created from the factory, by storing them in variables...var dupe3 = dupeFactory(3), dupe6 = dupeFactory(6)names.map(dupe6)
_scicomp.20182
I was reading about Petrov-Galerkin Enrichment Method for Darcy equations. Here are a couple papers that discuss this in detail:A PetrovGalerkin enriched method: A mass conservative finite element method for the Darcy equation.A Symmetric Nodal Conservative Finite Element Method for the Darcy Equation.However, I am not sure I understand what they are doing completely and would like some help understanding how they are constructing these multiscale or enrichment functions.From what I understand, it seems they are enriching the $P_1$ velocity by an $RT_0$, but what exactly does this mean? Specifically, what is meant when they correct edge residuals? Because I would like to implement this in something like FEniCS (if possible) but in order to do that I need to understand this method completely.
Petrov-Galerkin enrichment method for Darcy equation
finite element;fenics
null
_webmaster.5718
I have set up a new drupal site, and I have added an Image field to the default content type story using CCK and ImageField. This issue is that I can view the images when logged into my admin account, but when I try to view the images when logged out (like most, if not all viewers of this site would be), they don't appear.I have check permissions and I can't find anything that looks like the problem.Thanks!
Pictures are not displaying to anonymous users on Drupal, using ImageField!
drupal
null
_codereview.36643
Enter risk!This program will roll dice for the game of Risk. The initial input is two numbers separated by a space and if the attackers wish to do a blitz they can add one more space and an ! to get a positive attack modifier but are committed for an all or nothing fight.package riskdieroll;import java.awt.Component;import java.util.Arrays;import java.util.Collections;import javax.swing.JOptionPane;public class RiskDieRoll { private static Component frame; public static void main(String[] args) { int spcCnt, atck1, dfnc1, rollCnt, atck2 = 0, dfnc2 = 0, valHold, atckMod; String intInpt, Lsr; while(true) { boolean k = false; Lsr = ; intInpt = JOptionPane.showInputDialog(Please enter the a + mount of attackers then the number of\ndefenders separa + ted by a space., atck2 + + dfnc2); spcCnt = rollCnt = 0; valHold = intInpt.length(); atckMod = 6; if(0 0.equals(intInpt)) { break; } for(int i = 0; intInpt.charAt(i) != ' '; i++) { spcCnt++; } atck2 = atck1 = (int)Double.parseDouble(intInpt.substring(0 , spcCnt)); if(intInpt.charAt(valHold - 1) == '!') { k = true; atckMod = 7; valHold -= 2; } dfnc2 = dfnc1 = (int)Double.parseDouble(intInpt.substring(spcCnt + 1 , valHold)); Integer[] z = new Integer[3], y = new Integer[2]; if(atck1 < 2) { JOptionPane.showMessageDialog(frame, INVALID ATTACK! You need + at least two armys to make an attack!); atck2 = dfnc2 = 0; } else if(dfnc1 < 1) { JOptionPane.showMessageDialog(frame, INVALID INPUT! There must + be at least one defending army!); atck2 = dfnc2 = 0; } else { do { rollCnt = 0; for(int i = 0; i < 3; i++) { z[i] = (int)Math.ceil(Math.random() * atckMod); } for(int i = 0; i < 2; i++) { y[i] = (int)Math.ceil(Math.random() * 6); } Arrays.sort(z, Collections.reverseOrder()); Arrays.sort(y, Collections.reverseOrder()); while(dfnc2 > 0 && rollCnt < 2 && atck2 > 1) { if(y[rollCnt] >= z[rollCnt]) { atck2--; } else { dfnc2--; } rollCnt++; } }while(k && (dfnc2 > 0 && atck2 > 1)); if(dfnc2 < 1) { Lsr = \n\nDefenders have lost!!; } else if(atck2 < 2) { Lsr = \n\nAttackers have been repelled!!!; } JOptionPane.showMessageDialog(frame, Attacking force now at + atck2 + (Lost + (atck1 - atck2) + ) + \nDefence force now + at + dfnc2 + (Lost + (dfnc1 - dfnc2) + ) + Lsr); if(!.equals(Lsr)) { atck2 = dfnc2 = 0; } } } }}
Possible improvements to Risk board game?
java;game;dice;battle simulation
This code turned out to be a great exercise in refactoring, primarily usingExtract MethodReduce Scope of VariableExtract ClassIntroduce Explaining VariableSelf Encapsulate FieldHere's my goal:public class RiskDieRoller{ ////////////////////////////////////////////////////////////////////// private static class Strength { public int attack; public int defence; public int attackMod = 6; public Strength() {} public Strength(Strength other) { this.attack = other.attack; this.defence = other.defence; this.attackMod = other.attackMod; } public void blitz() { this.attackMod = 7; } public boolean isBlitz() { return this.attackMod == 7; } public String toString() { return Attack + this.attack + Defence + this.defence + AttackMod + this.attackMod; } } ////////////////////////////////////////////////////////////////////// // public static void main(String[] args) { RiskDieRoller roller = new RiskDieRoller(); Strength before = new Strength(); while (null != (before = roller.prompt(before))) { Strength after = roller.play(before); boolean isDecisive = roller.report(before, after); before = isDecisive ? new Strength() : after; } }}I've renamed the class to RiskDieRoller and introduced a Strength class to help tame the proliferation of variables. The main() function just outlines how the program flows.It's now just a simple matter of filling in the blanks. PromptYou failed to handle the Cancel button a NullPointerException occurs. You handle 0 0 as a special case, but what if there is gratuitous extra whitespace? Also, if the exclamation mark is not preceded by a space, then Double.parseDouble() barfs. Anyway, you should be calling Integer.parseInt() instead.In any case, analyzing the string character by character is tedious, error prone, and unforgiving of variations in the user-provided input. Just use a regular expression.private static final Pattern INPUT_RE = Pattern.compile(^\\s*(\\d+)\\s+(\\d+)\\s*(!)?\\s*$);public Strength prompt(Strength before){ do { String input = JOptionPane.showInputDialog(Please enter the + number of attackers then the number of\ndefenders + separated by a space., before.attack + + before.defence); if (null == input) { return null; } Matcher matcher = INPUT_RE.matcher(input); if (matcher.matches()) { Strength s = new Strength(); s.attack = Integer.parseInt(matcher.group(1)); s.defence = Integer.parseInt(matcher.group(2)); if (null != matcher.group(3)) { s.blitz(); } if (s.attack == 0 && s.defence == 0) { return null; } if (s.attack <= 1) { output(INVALID ATTACK! You need + at least two armies to make an attack!); } else if (s.defence <= 0) { output(INVALID INPUT! There must + be at least one defending army!); } else { return s; } } } while (true); // Repeat until input passes validation}private void output(String message){ JOptionPane.showMessageDialog(null, message);}It's not necessary to have a null Component instance variable; you can just pass a literal null to .showMessageDialog().PlayThis part of the code is more or less the same as before, but with nicer variable names. I've changed (int)Math.ceil(Math.random() * ) to Random.nextInt().private Random random = new Random();public Strength play(Strength before){ Strength s = new Strength(before); // Return a copy Integer[] attackRolls = new Integer[3], defenceRolls = new Integer[2]; do { for (int i = 0; i < 3; i++) { attackRolls[i] = 1 + random.nextInt(s.attackMod); } for (int i = 0; i < 2; i++) { defenceRolls[i] = 1 + random.nextInt(6); } Arrays.sort(attackRolls, Collections.reverseOrder()); Arrays.sort(defenceRolls, Collections.reverseOrder()); for (int rollCnt = 0; rollCnt < 2; rollCnt++) { if (s.defence <= 0 || s.attack <= 1) { return s; } if (defenceRolls[rollCnt] >= attackRolls[rollCnt]) { s.attack--; } else { s.defence--; } } } while (s.isBlitz()) return s;}Strictly speaking, you don't have to add 1 to .nextInt(), but it's more human-friendly to do so.ReportAgain, the main difference is in the management of variables. This function now has to return true if the battle was decisive. Arguably, that violates the single-responsibility principle, and could be improved further.In your original code, you checked for dfnc2 > 0 to continue the battle and dfnc2 < 1 to report annihilation of the defenders. I've changed this to s.defence <= 0 to check for termination of the battle and after.defence <= 0 to report annihilation, so that the similarity is apparent.I think String.format() is more readable than concatenation.public boolean report(Strength before, Strength after){ String verdict = (after.defence <= 0) ? \n\nDefenders have lost!! : (after.attack <= 1) ? \n\nAttackers have been repelled!!! : ; output(String.format(Attacking force now at %d (Lost %d)\n + Defence force now at %d (Lost %d) + %s, after.attack, before.attack - after.attack, after.defence, before.defence - after.defence, verdict)); return !verdict.isEmpty();}Nitpicksarmys armiesa + mount of attackers number of attackers (because it's a countable noun)
_unix.37052
I have the following files in a directory:-rw-r--r-- 1 smsc sys 46 Apr 22 12:09 bills.50.1.3G.MO.X.20120422120453.Z-rw-r--r-- 1 smsc sys 28 Apr 22 12:15 bills.50.1.3G.MO.X.20120422120953.Z-rw-r--r-- 1 smsc sys 46 Apr 22 12:20 bills.50.1.3G.MO.X.20120422121453.Z-rw-r--r-- 1 smsc sys 46 Apr 22 12:25 bills.50.1.3G.MO.X.20120422121953.ZWhere the fifth column is the file's size. I wish to delete all files which size is 46. In order to filter out these files I used the following command:ls -ltr | awk '$5 ~ /46/ {print $0}'Which works fine. But now I want to delete all files which were filtered out, so I add the following to the above command:ls -ltr | awk '$5 ~ /46/ {print $0}' | xargs rmHowever it gives me the following error:rm: invalid option -- wIt seems that I have to use find over ls so I will get the output in the below format:./bills.50.1.3G.MO.X.20120421050453.Z./bills.50.1.3G.MO.X.20120421154953.Z./bills.50.1.3G.MO.X.20120419133452.ZBut then I have no way to filter the files by its parameters.How this task could be done?
How to delete files filtered out by awk
find;awk;xargs
You have two bugs:You are comparing for a size that contains 46; you want it to be equal to 46.You are printing the entire line, when you want only the filename.And an additional issue: what is the point of -ltr to sort the ls output when you aren't using the sort order?You want to do something likels -l | awk '$5 == 46 {print $9}' | xargs rmExcept you don't want to do that, because while it might be safe at the moment, parsing ls output is unreliable. Use an appropriate tool such asfind . -maxdepth 1 -size 46c -delete # requires GNU find(Doing this portably is more annoying, since POSIX find doesn't have -maxdepth or -size that operates in units other than blocks. Better to write a script in a Perl/Python/Ruby/etc. that can use a proper directory scan that won't get in trouble with special characters in filenames.)
_unix.189087
I have a HP Compaq 8200 PC with Intel i5 CPU. I have enabled VT-x in BIOS:..and CPU supports VT-x as it has vmx flag present in /proc/cpuinfo. I have loaded the kvm LKM:root@VM-host:~# modprobe -v kvminsmod /lib/modules/3.2.0-4-686-pae/kernel/arch/x86/kvm/kvm.ko root@LS15-C-LAB-VM-host:~# lsmod | grep kvmkvm 239136 0 root@VM-host:~# ..but if I executed qemu with -enable-kvm option, it complained that:Could not access KVM kernel module: No such file or directoryfailed to initialize KVM: No such file or directoryNo accelerator found!/dev/kvm file was is indeed missing:root@VM-host:~# ls -l /dev/kvmls: cannot access /dev/kvm: No such file or directoryroot@VM-host:~# Once I installed the qemu-kvm package, I was able to start the qemu with -enable-kvm option. As I had understood, kvm support is merged into qemu and all that is needed for qemu is kvm LKM. Why is qemu-kvm package needed in Debian Wheezy when running qemu with -enable-kvm option?
Why is qemu-kvm needed in Debian Wheezy when running qemu with -enable-kvm option?
kvm;qemu
qemu-kvm was indeed merged into QEMU, but that happened in version 1.3. Debian Wheezy ships QEMU 1.1.2 which still needs qemu-kvm for KVM support.
_webmaster.26066
I'm new to iPad application development, but I am an experienced Web application developer in ASP.net. I want to develop fine applications for the iPad, but I want to learn from scratch.Please suggest me some online tutorial links or guide me through the right path for starting and learning development faster. I have less time and have to learn and develop more.
Creating iPad applications faster
iphone
null
_unix.2510
I've got an old VAXstation 3100 Model 76, and I'd like to install OpenBSD/vax 4.7 on it.I've got two drives in it, an RZ23 (104MB) and a another 1.09GB. Now, since the 1.09GB is too large for an operating system to boot from (VAXen have that magical 1.072GB boundary), I'd like to use the 104MB drive as / partition, and all other partitions, including swap should go on to the other drive.But how do I do this with the OpenBSD install, since it lets me chose one disk only?I tried installing NetBSD/vax 5.0.2 beforehand, but sysinst segfaults right after I give the OK to install the sets.The VAXstation has the both hard drives I mentioned above and 16MB RAM (which I'd like to expand some day). The machine is otherwise in perfect working order, expect the NVRAM and RTC don't work any more, I'll change them (new chip is already ordered).In case you'd advice another OS (aside from OpenVMS), you might give me hints here, too.
How to install OpenBSD/vax 4.7 on multiple disks?
openbsd;netbsd;vax
Are you sure it only lets you use one disk?It asks you for a root disk to install the bootloader. You should select the smaller disk and select manual partitioning. Read the manual for disk label or, if you know what you are doing, the installer help.After you set this disk up, other disks should be offered for setup in a list. Enter the name of the correct disk and follow on to disklabel and add the remaining partitions in that disk.I've only ever used the emulated VAX in simh, but I doubt there is any difference as long as both disks are actually detected correctly.
_scicomp.27590
I have written Poisson solvers using two different methods: A classic Jacobi scheme and one using the multigrid solver Hypre. I made up a couple of test cases ensuring the validity of those solvers.For both cases the domain is defined as $(x,y) \in [-1,1]^2$ with periodic boundary conditions. Also, the grids first and last point are the same:$$p(0,y) = p(N_x-1,y)$$$$p(x,0) = p(x,N_y-1)$$Test case 1$f_{rhs} = -8 \pi^2 \sin(2\pi x) \sin(2\pi y)$$p_{exact} = \sin(2\pi x) \sin(2\pi y)$For both solvers, the solution is 2$^{\mathrm{nd}}$ order accurate is space. No problems here so far.Test Case 2$p_{rhs} = e^{-10 (x^2 + y^2)}$$p_{exact}:$ No analytical solution, and therefore the numerical solution is differentiated using a high-order compact scheme and compared to $p_{rhs}$Note that in this case, $\int_V p_{rhs}dV \neq 0$ and therefore the problem is ill defined. Therefore, the $rhs$ must be modified:$p_{rhs} = e^{-10 (x^2 + y^2)} - \dfrac{\int_D e^{-10 (x^2 + y^2)} dx dy}{V}$where $V$ is the domain volume. The integral is computed using the Trapezoidal rule.This is where things get tricky. No matter how fine my grid is, $\left(p_{num}\right)_{xx} + \left(p_{num}\right)_{yy}$ never converge to $p_{rhs}$. When the grid is fine enough, the solvers converge, but the solution is off by ~20% while the overall profiles are relatively correct. When the grid is coarse, the Hypre solver simply diverges.QuestionHave I missed anything? Is my approach inconsistent/wrong?
Convergence problem for Poisson equation with periodic BC
convergence;poisson
null
_cogsci.8720
As a non-native English speaker I recently tried to understand difference in phrases to study and to learn. I found some explanations here on English language and usage SE, stating that learning is a subconscious activity. Then in some articles I've found, authors stated that language learning is subconscious and that acquiring knowledge and skill isn't the same [ also that learning language is actually learning a skill, while learning history is acquiring knowledge.] .So I got confused : is all learning subconscious or not? Is there a difference in learning language and learning anatomy, laws of physics or programming? Additionally some articles got me confused, especially those that want to sell you hypnosis DVDs and instruction manuals to boost your subconscious mind. Aren't we already equipped with proper subconscious mind?
Is all learning a subconscious activity?
learning;consciousness
We should not confuse the psychological terminology of consciousness, the subconscious and the unconscious with the lay meaning of activities being performed consciously or subconsciously.The distinction between conscious learning and subconscious acquisition of linguistic knowledge goes back to the Monitor Model that linguist Stephen Krashen developed in the 1970s and 1980s. According to this theory, human beings develop linguistic skills in two ways: either wesubconsciously acquire knowledge, without realizing that we do so (e.g. by growing up in a certain linguistic environment), or weconsciously learn (e.g. by memorizing lists of words in a foreign language).Krashen's theory has been both praised and criticized, but this is not the place to go into that debate. It should be enough to note that the hypothesis has as yet not been empirically proven.From a psychological point of view, learning of which acquisition is a part, namely that a response to a stimulus has been established is always not conscious. A conscious activity is one that we are aware of (like intentionally putting a book on a shelf), but learning, that is: the storing of information in the brain, takes place through processes of which we are unaware and in parts of our anatomy over which we have no control.For example, when you try to memorize a foreign word and its meaning, you cannot consciously put that knowledge in your memory like you can place a book on a shelf. What you must do, for example, is repeat the information until you no longer forget it. But you have no awareness of wether or not the storage was successful. You can only deduce that success from your ability to retrieve the information (i.e. correctly remember). A conscious storage would give you a direct (sensory) feedback of the storage process, similar to how your eyes show you wether or not the book is now on the shelf. If the placing of a book on a shelf worked subconsciously like storing knowledge in your brain, you'd have to retrieve the book from the shelf again to know that it had been put there. Until you took it off the shelf, you couldn't know if it was actually there.So to answer your question:For a psychologist, all learning is subconscious (but he would not use that word).
_unix.177975
In gedit on GNOME 3.14 (Fedora 21), using the mousewheel to scroll results in ordinary scrolling, whereas using the arrow keys or PageUp/PageDown results in smooth scrolling. How can smooth scrolling for the arrow keys/PageUp/PageDown be disabled in gedit?
How can keyboard smooth scrolling be turned off in gedit (GNOME 3.14/Fedora 21)?
fedora;gnome;gedit;scrolling
null
_unix.43974
In some programs percentage of copying large files get to 100% very fast and then I'm waiting much more before it goes next step. It's caused by buffer. How to I see amount of data that are going to be written?
How to get size of data that haven't been written to disk yet?
cache;disk
The term for that is dirty data (data that has been changed, but not yet flushed to permanent storage).On Linux you can find this from /proc/meminfo under Dirty:$ cat /proc/meminfo | grep DirtyDirty: 0 kB
_datascience.8294
How do we use one hot encoding if the number of values which a categorical variable can take is large ?In my case it is 56 values. So as per usual method I would have to add 56 columns (56 binary features) in the training dataset which will immensely increase the complexity and hence the training time.So how do we deal with such cases ?
One Hot encoding for large number of values
machine learning;data mining;classification;dataset;categorical data
null
_codereview.118247
For no particular reason, I wanted to create a function that would take a string and encrypt it via Caesar cipher. This function takes a string and shifts the letters left or right (in the alphabet) depending on the input. Shift right(2) for instance would be -ABCDEFGHIJKLMNOPQRSTUVWXYZCDEFGHIJKLMNOPQRSTUVWXYZABThe UDF:Option ExplicitPublic Function CaesarCipher(ByVal TextToEncrypt As String, ByVal CaesarShift As Long) As String 'Positive means shift to right e.g. A Shift 1 returns B Dim IsPositive As Boolean IsPositive = True If CaesarShift < 0 Then IsPositive = False CaesarShift = Abs(CaesarShift) Dim OutputText As String TextToEncrypt = UCase(TextToEncrypt) If CaesarShift > 26 Then CaesarShift = CaesarShift Mod 26 End If If IsPositive Then OutputText = ShiftRight(TextToEncrypt, CaesarShift) Else: OutputText = ShiftLeft(TextToEncrypt, CaesarShift) End If CaesarCipher = OutputTextEnd FunctionThe shifting functions:Private Function ShiftRight(ByVal ShiftString As String, ByVal ShiftQuantity As Long) As String Dim TextLength As Long TextLength = Len(ShiftString) Dim CipherText As String Dim CharacterCode As Long Dim AsciiIndex As Long Dim AsciiIdentifier() As Long ReDim AsciiIdentifier(1 To TextLength) For AsciiIndex = 1 To TextLength CharacterCode = Asc(Mid(ShiftString, AsciiIndex, 1)) If CharacterCode + ShiftQuantity > 90 Then CharacterCode = CharacterCode - 26 + ShiftQuantity ElseIf CharacterCode = 32 Then GoTo Spaces Else: CharacterCode = CharacterCode + ShiftQuantity End IfSpaces: AsciiIdentifier(AsciiIndex) = CharacterCode Next For AsciiIndex = 1 To TextLength CipherText = CipherText & Chr(AsciiIdentifier(AsciiIndex)) Next ShiftRight = CipherTextEnd FunctionPrivate Function ShiftLeft(ByVal ShiftString As String, ByVal ShiftQuantity As Long) As String Dim TextLength As Long TextLength = Len(ShiftString) Dim CipherText As String Dim CharacterCode As Long Dim AsciiIndex As Long Dim AsciiIdentifier() As Long ReDim AsciiIdentifier(1 To TextLength) For AsciiIndex = 1 To TextLength CharacterCode = Asc(Mid(ShiftString, AsciiIndex, 1)) If CharacterCode = 32 Then GoTo Spaces If CharacterCode - ShiftQuantity < 65 Then CharacterCode = CharacterCode + 26 - ShiftQuantity Else: CharacterCode = CharacterCode - ShiftQuantity End IfSpaces: AsciiIdentifier(AsciiIndex) = CharacterCode Next For AsciiIndex = 1 To TextLength CipherText = CipherText & Chr(AsciiIdentifier(AsciiIndex)) Next ShiftLeft = CipherTextEnd Function
Simple Caesar Cipher Function
vba;caesar cipher
Just some things that jump out at me:Standard VBA Naming conventions have camelCase for local variables, and PascalCase only for sub/function names and Module/Global Variables. This allows you to tell at a glance if the variable you're looking at is local to your procedure, or coming from somewhere else.I would probably use EncryptUsingCaesarCypher as your function name. It's more descriptive and closer to what it actually does.`Text = CaesarCypher(text)versus`Text = EncryptUsingCaesarCypher(text)Other than that, your naming is pretty solid.Why separate functions for ShiftLeft and ShiftRight? The code in both is heavily-repeated and could be easily combined into a Shift(ByVal shiftValue as Long) function that handles positive and negative. This also lets you cut out all that messing around with isPositve and Abs(shift)
_webmaster.69756
i want to enable SSL for my main website and sub-domain websites. for SEO reasons i need to redirect HTTP requests to HTTPS requests and i think i should do that using wild card redirect in htaccess file. But, i already HAVE a wild card redirect in my htaccess file as followRewriteCond %{HTTP_HOST} ^mscaspian.com$RewriteRule (.*) http://www.mscaspian.com/$1 [R=301,L]as you can see that will redirect Non-WWW version of my site to WWW version.i need to know how to utilize Both Redirects for my websites and domain
Wild card redirection for HTTPS and Non-www version
htaccess;https
Looks like you didnt escape the slashes in your directive. Putting backslashes before any / . or : should make it work. Also adding the ^ and $ on the wildcard helps. Heres what we use:Standard Domain: Perhaps there is a consolidated way, but this snippet should work for a standard domain. Change the target of the first rewrite to https if you need all to https mode:RewriteCond %{HTTP_HOST} ^example\.com$RewriteRule ^(.*)$ http\:\/\/www\.example\.com\/$1 [R=301,L]RewriteCond %{HTTPS_HOST} ^example\.com$RewriteRule ^(.*)$ https\:\/\/www\.example\.com\/$1 [R=301,L]Addon Domain: If you are trying to do this with an addon domain and want to redirect the subdomain utility scheme, this would do that. Again, change the target of first directive to https and it should force SSL:RewriteCond %{HTTP_HOST} ^addondomain\.example\.com$ [OR]RewriteCond %{HTTP_HOST} ^www\.addondomain\.example\.com$ [OR]RewriteCond %{HTTP_HOST} ^addondomain\.com$RewriteRule ^(.*)$ http\:\/\/www\.addondomain\.com\/$1 [R=301,L]RewriteCond %{HTTPS_HOST} ^addondomain\.example\.com$ [OR]RewriteCond %{HTTPS_HOST} ^www\.addondomain\.example\.com$ [OR]RewriteCond %{HTTPS_HOST} ^addondomain\.com$RewriteRule ^(.*)$ https\:\/\/www\.addondomain\.com\/$1 [R=301,L]Hope that helps!
_unix.269631
Assume I have a file A:fileA fileBSuppose I have now a file named:fileA_someprefix_20160101.txtNow I want to match all lines from A which prefix this filename, so I thought:FILE_NAME=fileA_someprefix_20160101.txt awk '$FILE_NAME ~ /^$1/' A.txtI tried different ways to escape the dollar sign, but it did not work.In all examples the field is part of the expression (left) instead of the regex.How do I a reverse start with?
AWK: How to put field ($1) inside regular expression to select all prefixes?
text processing;awk
null
_codereview.144394
I'm writing a weight training app that calculates a one rep maximum and it has several options including recording your lifts in pounds or kilograms. I'm trying my best to follow the MVC pattern but I'm not entirely sure where to do some calculating and formatting. I have a UITableView to display my Lift Log and when I load it, I'm converting the oneRepMaxWeight as needed to display all values in pounds or kilograms, depending on the user's current default units. I also round the numbers if the user's default is set to round (see formatForDisplay(value:): class LiftLogViewController: UIViewController, NSFetchedResultsControllerDelegate, DismissalDelegate { //MARK: IB outlets @IBOutlet var tableView: UITableView! @IBOutlet weak var navItem: UINavigationItem! let coreDataStack = CoreDataStack() var liftEvents = [LiftEvent]() var preferredUnits = UserDefaultsManager.sharedInstance.preferredUnits override func viewDidLoad() { super.viewDidLoad() let doneButton = UIBarButtonItem(title: Done, style: .Plain, target: self, action: #selector(self.dismissLog(_:))) self.navItem.rightBarButtonItem = doneButton tableView.allowsSelectionDuringEditing = true tableView.rowHeight = 88.0 tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 88.0 automaticallyAdjustsScrollViewInsets = false } func selectionDidFinish(controller: LiftSelectionTableViewController) { controller.dismissViewControllerAnimated(true, completion: nil) } func formatForDisplay(value: Double) -> String { let roundingIsOn = UserDefaultsManager.sharedInstance.preferredRoundingOption if roundingIsOn == true { let value = String(format:%.lf, value) return value } else { let value = String(format:%.1lf, value) return value } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let nav = segue.destinationViewController as! UINavigationController let vc = nav.topViewController as! LiftSelectionTableViewController vc.selectForFilter = true vc.dismissalDelegate = self } func segueToLogFilters(sender: AnyObject) { performSegueWithIdentifier(segueToLogFilters, sender: self) } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return liftEvents.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(liftEventCell, forIndexPath: indexPath) as! LiftLogTableViewCell let liftEvent = liftEvents[indexPath.row] cell.viewData = LiftLogTableViewCell.ViewData(liftEvent: liftEvent) if liftEvent.units != preferredUnits { let from = Unit(rawValue: cell.units.text!) let to = Unit(rawValue: preferredUnits!) let oneRepMaxWeight = Double(cell.oneRepMaxWeight.text!) let convertedMax = calculator.convertUnits(from!, to: to!, value: oneRepMaxWeight!) cell.oneRepMaxWeight.text = String(convertedMax) cell.units.text = preferredUnits } let formattedMaxWeight = formatForDisplay(Double(cell.oneRepMaxWeight.text!)!) cell.oneRepMaxWeight.text = formattedMaxWeight cell.liftName.textColor = UIColor(hexString: 232B35) cell.oneRepMaxWeight.textColor = UIColor(hexString: 232B35) cell.units.textColor = UIColor(hexString: 232B35) return cell }}I recently created a separate UITableViewCell class to get the conversion and formatting logic out of cellForRowAtIndexPath because I don't think it belongs there and I can't test it if it's in there. But then I found myself having to put this code into this new class and that seems just as bad:class LiftLogTableViewCell: UITableViewCell { @IBOutlet weak var liftName: UILabel! @IBOutlet weak var liftDetails: UILabel! @IBOutlet weak var liftDate: UILabel! @IBOutlet weak var oneRepMaxWeight: UILabel! @IBOutlet weak var units: UILabel! @IBOutlet weak var formula: UILabel! struct ViewData { let liftName: String let weightLifted: Double let repetitions: Int let liftDate: String let oneRepMaxWeight: Double let units: String let formula: String } var viewData: ViewData? { didSet { liftName!.text = viewData!.liftName liftDetails!.text = \(viewData!.weightLifted) @ \(viewData!.repetitions) liftDate!.text = on \(viewData!.liftDate) oneRepMaxWeight!.text = \(viewData!.oneRepMaxWeight) formula!.text = viewData!.formula units!.text = viewData!.units } }}extension LiftLogTableViewCell.ViewData { init(liftEvent: LiftEvent) { self.liftName = liftEvent.liftName self.weightLifted = Double(liftEvent.weightLifted) self.repetitions = Int(liftEvent.repetitions) self.formula = liftEvent.calculation.formulaName //change 'calculation' to 'forumla' for heaven's sake let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = yyyy-MM-dd let formattedDate = dateFormatter.stringFromDate(liftEvent.liftDate) self.liftDate = \(formattedDate) self.oneRepMaxWeight = Double(liftEvent.maxAmount) self.units = liftEvent.units }}Ultimately, my question is, if I'm trying to follow MVC, where should I put code to convert these values and format them as I'm creating my tableview cells? Would it make sense to create helper class(es) that handle these things?
Formatting data in a UIViewController in a weight-training app
mvc;swift;unit conversion;spring mvc
null
_softwareengineering.193991
I am developing enterprise iPad application which contained large amount of different bundle data in terms of group of images.Is it worth to stored as a compressed file format or normal set of individual files?I am not worrying about huge amount of data which is reside in the cloud.My concern is that cloud computing provider only charges depending upon the request not about how much data where stored.If I store single file in cloud then it make more request while using the app. So it will cost so much.Is it better to be stored as a compressed file in cloud?
Is it better to have file stored as a zip in cloud service?
ios;cloud computing;cloud
null
_unix.335752
Nplt user not have the permission to run the command crontab -lso I add this lines in visudoNplt ALL=(root) NOPASSWD: crontab -lbut I get this errorisudo: >>> /etc/sudoers: syntax error near line 21 <<<What now? ^Cvisudo exiting due to signal: Interruptwhat is wrong in my syntax?
linux + write syntax in visudo
linux;rhel;sudo
null
_unix.93205
I think this question explains itself. But here are some more details anyway:Many Linux distributions have live USB's which one can use to try and install that distro. However, that pen must often be formatted, and even afterwords, it can only have the purpose to install that one distribuition. Why can't one have a directory for each distro and have BIOS boot from that? (maybe including some file leading to other the files from which to boot, but not having them all laying in the top directory of that drive) How? Which distribuitions support that? Can you make such a file for BIOS to detect and find the bootable files for several distros? (then one should choose from which one to boot from, like when a computer has several operating systems)
Can one make a bootable device with several distros of Linux?
linux;distros;live usb;bios;bootable
It is certainly possible to roll your own version of this concept with Grub. However there are also tools that can make the process much easier.PenDriveLinux lists several tools. Of those I have had good luck with Yumi, which is Windows based, and MultiSystem which is Linux-based. The MultiSystem project website is in French, but PenDriveLinux has good instructions. I've created multi-distro USB keys with both of these with good results.
_unix.15916
I am trying to set up a system to prepare a Linux system on a virtual machine and then deploy it onto an SD card. The target system has an Atom processor, so there aren't architecture compatibility concerns.Do any of the mount points have to be in a special, physical location for this to work or can GRUB grok the filesystem?How do I set up the SD card to boot this system using GRUB?Would it be better to rsync the filesystem over or dd a filesystem image? I much prefer the former because I don't have to change my VM much when going between different card sizes.EDIT:I assume that I'll have to prepare the card before hand using something like parted, then I'll have to install GRUB to it, which isn't a big deal.The major question is, will GRUB find the kernel if it isn't in a guaranteed, physical place on the partition? In other words, is GRUB smart enough to read an ext2, ext3, or ext4 partition and find the appropriate mount points?My disk will look something like this (2 partitions):[GRUB] [grub loader stuff] [GRUB partition] [OS partition]
Preparing a Linux image in a virtual machine
linux;grub;boot loader;cloning
When Grub boots, it loads itself using information provided by the BIOS. As long as all the pieces are on the same disk this should work seamlessly.When Grub loads Linux, it can find the kernel on the same disk as Grub or by searching through the available disks. Again if you put the kernel on the same disk as Grub this should work seamlessly.When the Linux kernel goes to mount the root filesystem, it uses its own disk numbering. Grub passes a command line argument to the kernel so that it knows where to find the root filesystem; the argument has to be in terms of what the kernel understands. Disk numbers (e.g. sda, sdb, hda, etc.) are unpredictable if you move from system to system. The easiest way to make sure this will work is to put the root filesystem (and any other filesystem or swap space) on LVM. At boot time (specifically at the initrd/initramfs execution stage) the system will look through all available LVM physical volumes, assemble the groups, and that gives access to all the logical volumes they contain. Since LVM volumes have names and not disk numbers, it doesn't matter what the disk numbers are.Grub has to know the exact physical location on the disk of its pieces. You can't make a bootable SD card by just copying files onto it, you have to make a bootloader installation. To cope with different-size devices easily, a good way is to make a fixed-size partition at the beginning of the disk for the OS, and use the rest of the space as an extra data partition. On that topic, see Cloning a bootable USB stick to a different-size stick.
_codereview.70115
I downloaded source code of cryptosms and implemented the ECIES cipher in my work for Java mobile.I doubt validity of this step (full code of my method is below): engine.init(true, (CipherParameters) k, (CipherParameters) pubKey, new IESParameters(Z.getX().toBigInteger().toByteArray(), R .getQ().getEncoded(), 64)); //here is the problemIn particular the line that I commented: is that correct way to implement ECIES? All works ok but I have a suspect that it doesn't share the secret KDF in secure mode.The project is dead and I can't contact authors. public byte[] cifra(byte[] data, byte[] key) throws Exception { boolean failure = true; ECDomainParameters domainParams= EllipticUtils.getECDomainParameters(); IESEngine engine = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac( new SHA1Digest())); ECPoint publicPoint = domainParams.getCurve().decodePoint(key); ECPublicKeyParameters pubKey = new ECPublicKeyParameters( publicPoint, domainParams); ECPrivateKeyParameters k = null; ECPublicKeyParameters R = null; ECPoint Z = null; SHA256SecureRandom PRNG = SHA256SecureRandom.getIstance(); PRNG.initPRNG(); while (failure) { BigInteger privNum = new BigInteger(PRNG.getPRNG() .generateSeed(16 )); k = new ECPrivateKeyParameters(privNum, domainParams); // this is // just a container R = EllipticUtils.generatePublicKey(k); // R = kP // calculate Z=hkQ BigInteger z = new BigInteger(domainParams.getH().toByteArray()); // z=h z = z.multiply(privNum); // z=hk Z = pubKey.getQ(); // Z=Q if (Z instanceof ECPoint.F2m) { ECPoint.F2m Z2 = new ECPoint.F2m(Z.getCurve(), Z.getX(), Z .getY()); // clone Z = Z2.multiply(z); // Z=zQ <=> Z=hkQ } if (Z instanceof ECPoint.Fp) { ECPoint.Fp Z2 = new ECPoint.Fp(Z.getCurve(), Z.getX(), Z .getY()); // clone Z = Z2.multiply(z); // Z=zQ <=> Z=hkQ } if (!Z.isInfinity()) failure = false; // see step 2 } // step 3 and 4: // setup KDF(xz,R) - see new IESParameters(...) // pass the parameters for step4 engine.init(true, (CipherParameters) k, (CipherParameters) pubKey, new IESParameters(Z.getX().toBigInteger().toByteArray(), R .getQ().getEncoded(), 64)); //here is the problem // step 4 generate C and t byte[] cAndT = engine.processBlock(data, 0, data.length); // collect the result in format // byte[0] = length of R (encoded) // R in encoded form // C and t as coming from the engine byte[] publicBytes = R.getQ().getEncoded(); byte[] out = new byte[1 + publicBytes.length + cAndT.length]; out[0] = (byte) publicBytes.length; // WARN this will crash if // key.length > 255 System.arraycopy(publicBytes, 0, out, 1, publicBytes.length); System.arraycopy(cAndT, 0, out, 1 + publicBytes.length, cAndT.length); return out;}
Is this implementation of the ECIES cipher correct?
java;cryptography;mobile
null
_ai.2769
Can silicon based computers create A.I. per definition of what intelligence is?Or does silicon based computers only create human mimic?If silicon based computers only create human mimic, are human mimic intelligence per definition?If not, how can we create A.I. per definition of what intelligence is?
Can silicon based computers create A.I. per definition?
neural networks;machine learning;deep learning;research;ai design
null
_webmaster.108758
In our store ruban.com all products of MAC brand are out-of-stock. But this is a very famous brand in region with a lot of searches.Is it a good Idea to buy google-adwords for this brand?
Could I buy google-adwords for out-of-stock products?
seo;google adwords
null
_unix.343714
**Relevant details:**OS: Ubuntu 16.04File System: Ext3/LUKSRecovery software attempted: PhotoRecCorrupt drive: Hard disk drive 200GB SATAI've attempted to perform a file recovery from a what seems to be a corrupt hard drive. The files which were recovered, were given filenames which are not the original filenames. I assume PhotoRec sequentially names any files recovered. How do I recover the files and keep the original filenames intact?Question: Is it possible to recover the files and keep the original file names intact?
Recovered files using PhotoRec
data recovery;ext3
null
_cs.52488
Disclaimer: I know there are similar sounding questions already here and on Stackoverflow. But they are all about collisions, which is not what I am asking for.My question is: why is collision-less lookup O(1) in the first place?Let's assume I have this hashtable:Hash Content-------------ghdjg Data1hgdzs Data2eruit Data3xcnvb Data4mkwer Data5rtzww Data6Now I'm looking for the key k where the hash function h(k) gives h(k) = mkwer. But how does the lookup know that the hash mkwer is at position 5? Why doesn't it have to scroll through all keys in O(n) to find it? The hashes can't be some kind of real hardware addresses because I'd lose the abbility to move the data around. And as far as I know, the hashtable is not sorted on the hashes (even if it was, the search would also take O(log n))?How does knowing a hash help finding the correct place in the table?
Why is a (collision-less) hashtable lookup really O(1)?
complexity theory;hash;hash tables;performance
The hash function doesn't return some string such as mkwer. It directly returns the position of the item in the array. If, for example, your hash table has ten entries, the hash function will return an integer in the range 0–9.
_unix.266860
if the format is:route add -host 192.168.1.20 gw 10.1.1.20 dev eth0:1I know, It will route 192.168.1.20 to 10.1.1.20Then, what's the dev eth0:1 mean?
Meaning of route add -host xxx.xxx.xxx.xxx dev eth0:1
linux;networking;route;iproute
The inclusion of 'dev eth0:1' forces the kernel to use the eth0:1 interface for traffic matching the route specification.Also in this case, the interface specification is for an alias interface or label configured on eth0.
_codereview.39982
I am creating an API for consumption by other developers to interface with an internal framework. My goal is to be able to have the developers type something like:profile.setPreference(new GroupPreference(id));orUserPreference preference = new UserPreference();preference.setDefaultInbox(nameOfInbox);// set any other options, classes simplifiedprofile.setPreference(preference);The internal framework has all preferences persisted in the same manner. A user profile can be either a set of preferences specific to them (UserPreference) or a relation to a group preference using an ID (GroupPreference).An example of current API usage:// Context object Profile profile = userService.getProfile(accountName);// Preference returned here is immutablePreference preference = profile.getPreference();preference.getDashboardOptions();preference.getDefaultInbox();// etc..// To modify a users preferencesUserPreference userPreference = new UserPreference(preference);userPreference.setDefaultInbox(newInbox);// etc..profile.setPreference(userPreference);// Or to link it to a group preferenceprofile.setPreference(new GroupPreference(groupPreferenceId));I handle saving of the preference information through a PreferenceManager as a part of updating the overall profile:preferenceManager.savePreference(preference, profileContext);Now for the questions:The protected save method feels extremely cludgy but I didn't want to have any methods in the interface that potentially exposes implementation details. Is there a better way?How is this design overall? Something need to be reorganized?public abstract class Preference { /** * Provides access to DashboardOptions object to manage what options are enabled * and disabled on the users dashboard. * * @return DashboardOptions object */ public abstract DashboardOptions getDashboardOptions(); /** * Gets the default inbox for the user. * * @return Default inbox */ public abstract String getDefaultInbox(); /** * Method that will be overridden to handle saving of the preference. * * @param profile ProfileContext passed in to provide information when saving preferences * @param service PreferenceService object that handles saving of preferences */ protected abstract void save(ProfileContext profile, PreferenceService service);}public class GroupPreference extends Preference { private Long groupPreferenceId; public GroupPreference(Long groupPreferenceId) { this.groupPreferenceId = groupPreferenceId; } public Long getPreferenceId() { return groupPreferenceId; } @Override public DashboardOptions getDashboardOptions() { return null; } @Override public String getDefaultInbox() { return null; } @Override protected final void save(ProfileContext profile, PreferenceService service) { service.setUserPreference(profile.getId(), groupPreferenceId); }}public class UserPreference extends Preference { private UserDashboardOptions options; private String defaultInbox = ; public UserPreference() { this.options = new UserDashboardOptionsImpl(); } public UserPreference(Preference preference) { this.options = new UserDashboardOptionsImpl(preference.getDashboardOptions()); } @Override public UserDashboardOptions getDashboardOptions() { return options; } @Override public String getDefaultInbox() { return defaultInbox; } public void setDefaultInbox(String defaultInbox) { this.defaultInbox = defaultInbox; } @Override protected final void save(ProfileContext profile, PreferenceService service) { // The SubjectPreference is part of an internal framework I have to interface with SubjectPreference subjectPreference = service.createSubjectPreference(profile); service.saveSubjectPreference(subjectPreference); }}public class PreferenceManager { public void savePreference(Preference preference, ProfileContext profile, PreferenceService service) { preference.save(profile, service); }}
Java API without exposing implementation details
java;object oriented;api
null
_webmaster.101751
I am new to PHP and I'm currently learning about PHP from the point of view of managing a web server. I believe that PHP extensions are like plugins which enable added functionality to the default PHP set-up - I know this is a very basic overview but is my simplification correct?I have also noticed PECL and PEAR on my cPanel set-up and have not even began to enquire what they are as I want to understand the basics of how PHP works. I'd value any input just to help my novice brain process this.
What are PHP extensions?
web hosting;php;cpanel
The simple answer is that most of the PHP functionallity is in the basic setup and you probally don't need to worry about this.But, extensions are exactly as they sound like, they extend PHP functionallity. You have a MYSQL extension which allows you to connect to a database with premade functions (this extension is mostly on by default, unless you have a bad hoster). If you do phpinfo(); in a php file, there will be a section called 'modules loaded', which lists all of them. Most of the usefull ones are already included.Turning these extensions on is possible via various methods, often in the php.ini (the settings file for PHP). If you want to change this, you'll need root access to the server, which you often dont have with shared hosting (but, again, you don't really need this when you just begin).
_scicomp.27243
I found this one, but does not work: http://www.karlin.mff.cuni.cz/~hron/warsaw_2014/pl2014_lecture5.pdf
Anyone knows where I can find a simple FEniCS code where I can understand basic implantation?
finite element;fenics
null
_softwareengineering.279849
We have a large Java project (1m+ SLOC) with mixed whitespace - some files have tabs and some have spaces. It's tricky to make my editor work with whichever file I happen to be editing. We are going to choose a convention and enforce it in future. The question is whether I should make one commit to correct the whitespace in the whole project after the decision is made.Git can ignore changes in whitespace, so in future to compare with older revisions we would have to use git diff -w. However, if and when we update a file in a piecemeal way we would still have to use git diff -w.For the record, this is an Eclipse RCP project, so using an IDE other than Eclipse is not really sensible.Edit: There are some good answers here, but they tend to discuss how I should go about this rather than whether this is a good idea or whether I should just leave well alone, which is what I'm really interested in.
Should I edit a codebase's whitespace to conform to a coding style?
java;conventions;whitespace
What do you mean by my editor? And what do you mean by git -w? Are you using an editor and command line tools instead of an IDE? May I recommend IntelliJ IDEA? It is the best java IDE ever, and it has no problem with either kind of whitespace, or even with mixed whitespace within the same file.Generally, if a massive change has to be made to the code base, like changing the formatting, it should be done all at once and as early as possible. If you don't do that, then files will keep being committed in the future for no reason other than whitespace changes, unnecessarily bloating the history lists, and forcing you to often request diffs of files only to be told files differ only in whitespace. Also, it will never be obvious whether a file was committed due to actual changes or only due to whitespace changes, so if two or more developers happen to have different whitespace and/or formatting settings by mistake, it will take you some time and several commits where one developer is undoing the whitespace changes of another until you realize that this discrepancy exists.By reformatting and committing everything at once, the revision number of that commit (which will from that day on be known as The Great Big Reformatting) will be memorized by everyone, so whenever you see that revision number you will know to not even request a diff. Plus, from that moment on, everyone will know that subsequent commits due to whitespace changes only should not be made, because they are obviously the result of a configuration mismatch between developers.AmendmentNow, on the question of whether you should convert the entire code base to conform to a particular coding style, this is not an easy thing to answer without knowing the particulars of your situation. The obvious answer, which anyone out there will tell you, is that a consistent coding style is important, and that even a bad (by whatever standard) but consistent style is better than an inconsistent style. However, there are some practical questions to be asked first:Do most of the important contributors at your workplace agree? Are there any contributors who, despite being a minority, might rage-quit if you proceed with this? And how important are they?How big of a variety of styles do you have? Is it only tabs vs. spaces, or does it include other major aspects of coding style like Allman vs. Egyptian braces? People should be flexible enough to not mind a small variety.But mostly: Is it really necessary? I mean, in my current job, each developer is working on a specific, clearly delineated subset of the code base, so I don't delve (much) into other people's code, and nobody delves into my code, so it does not really matter that we have vastly different styles. It neither picks my pocket nor breaks my leg that a colleague wraps his lines at column 80. (Ssssh, he probably does not know how to change the relevant setting.) The situation would be quite different if we had developers whose job involved frequently dealing with other people's code. If you do have such a situation, and if the coding styles vary so much as to make it hard for them to do their job, then you probably should enforce a single coding style for everyone. Otherwise, perhaps not.One more final note:In theory, it should be possible to resolve this issue with technical means so that a) different developers can work on the same code, and yet b) each developer gets to enjoy whatever coding style he or she prefers. The way this would (in theory) be accomplished would be by having code formatted to your preferred style when updating from the version control system, and re-formatted to the project style right before committing. Unfortunately, as of today, there are no tools that will do this as far as I know. IntelliJ IDEA gets close by supporting multiple styles, including a personal style and a project style, but it is not fully automated: you still get to browse unmodified code in project style, if you re-format any files to your personal style they will unfortunately appear as modified with respect to the pristine copies, (which is probably a shortcoming of the version control system and not of IDEA,) and the (optional of course) step which re-formats files back to project style when committing leaves all of your local copies in project style again. If anyone knows of anything that achieves more than that, please do say.
_unix.237435
Am using a script in ksh to get a date 91 days prior to today using datecalc on a Solaris 10 server. What would be the equivalent to this in Linux ?month=`datecalc -a $(date +%Y %m %d) - 1 |awk {'print $2'}`day=`datecalc -a $(date +%Y %m %d) - 91 |awk {'print $3'}`year=`datecalc -a $(date +%Y %m %d) - 1 |awk {'print $1'}`
Datecalc equivalent for Linux
shell script;date
null
_softwareengineering.293578
I have started freelancing for couple of weeks and have done few projects.While doing it I found myself in risky situation when client ask progress and also want to see it done. which means I have to send them what work I done to the date. So they can know their project is on progress and will be completed on time.But on the other end If I send them almost done project and if they think they don't need my help they could just leave the project without paying.One thing I have been thinking is to ask for small Milestone payment before every regular progress. (What if they want update everyday?)It is possible to have bug while project is on progress and they might refuse to pay subsequent milestone.So..How do you report and demonstrate project without risk of losing code (work done) before you are paid? (In situation where you are freelancing and client is at remote location)
Demonstrate or Report a project to Client while freelancing
freelancing;client relations
First of all I would recommend doing either up front payments (for small amounts, which I define < $1000) or milestone payments with clearly defined milestone, so you aren't worried about being paid and they aren't worried about you walking off with the money without doing any work. Now it depends on what you are working on as to how to keep the client up to date. Often it is good enough to send an email saying I've finished X and Y and have started on Z.If you are doing a web project you can have a test server that has the latest progress running that they can look at. You can also use something like Trello which gives them a visual on the tasks/features that you have done, are currently working on, and still pending.Clear communication is necessary right from the word go. Agree on exactly what you will be delivering and when, and have it in writing. They will change their minds. That's natural, and as good customer service you should change what you are delivering to meet their needs, but the agreement will give you the leverage to actually get paid for what you have done, rather than having them say I didn't ask for that I'm not paying. This also requires you to be reliable and deliver things when you say you are going to. And as soon as you think you won't make that deadline, you need to say something and make them aware of the fact that it is taking longer than expected.
_webmaster.105490
I couldn't find the exact answer for this particular issue. I have two add-on domains https://domain001.com and https://domain002.com hosted in /public_html/domain001/ and public_html/domain002/A little background: I had to place robots.txt file for domain001.com in /public_html/ because for some reason I hadn't been able to verify the robots.txt file in google search console when I placed it in /public_html/domain001/.Now domain002.com is using robots.txt file of domain001.com, although I have a separate robots.txt file for domain002.com in /public_html/domain002/.As I've learned from similar topics here, I need to conditionally serve a different robots.txt file based on which domain has been accessed. How can I do that? What code should I place in .htaccess? I'm not a developer. So I would greatly appreciate if you provided more details in your answers.Thank you for your time.P.S. I'm using wordpress.
How to serve a corresponding robots.txt file for each website in the same directory?
wordpress;robots.txt
null
_unix.315114
I've installed a new Manjaro Linux 16.06.1 on an Aspire V15 Nitro Vn7-572G-56VP. Before, there was a Linpus Linux installed. I recreated all partitions and installed Manjaro. I also attempted the manual grub install from https://wiki.manjaro.org/index.php/Restore_the_GRUB_Bootloader . grub-install --recheck ran without errors.But now the laptop boots and cannot find any bootable media. No grub boot menu is shown.I also tried enabling Secure Boot and adding grubx64.efi to the trusted files.What can I do?Here is some info that might be useful (sda is an SSD, sdb is a HDD):>>> bootinfoscript Boot Info Script 0.61 [1 April 2012]============================= Boot Info Summary: =============================== => Grub Legacy is installed in the MBR of /dev/sda and looks at sector 59737416 of the same hard drive for the stage2 file, but no stage2 files can be found at this location.. => No boot loader is installed in the MBR of /dev/sdb.sda1: __________________________________________________________________________ File system: vfat Boot sector type: FAT32 Boot sector info: No errors found in the Boot Parameter Block. Operating System: Boot files: /efi/manjaro/grubx64.efisda2: __________________________________________________________________________ File system: ext4 Boot sector type: - Boot sector info: Operating System: Manjaro Linux () () Boot files: /boot/grub/grub.cfg /etc/fstab /boot/syslinux/syslinux.cfgsdb1: __________________________________________________________________________ File system: ext4 Boot sector type: - Boot sector info: Operating System: Boot files: ============================ Drive/Partition Info: =============================Drive: sda _____________________________________________________________________Disk /dev/sda: 238.5 GiB, 256060514304 bytes, 500118192 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisklabel type: gptPartition Boot Start Sector End Sector # of Sectors Id System/dev/sda1 1 500,118,191 500,118,191 ee GPTGUID Partition Table detected.Partition Start Sector End Sector # of Sectors System/dev/sda1 2,048 8,390,655 8,388,608 EFI System partition/dev/sda2 8,390,656 500,117,503 491,726,848 Data partition (Linux)Drive: sdb _____________________________________________________________________Disk /dev/sdb: 465.8 GiB, 500107862016 bytes, 976773168 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisklabel type: gptPartition Boot Start Sector End Sector # of Sectors Id System/dev/sdb1 1 976,773,167 976,773,167 ee GPTGUID Partition Table detected.Partition Start Sector End Sector # of Sectors System/dev/sdb1 2,048 976,773,119 976,771,072 Data partition (Linux)blkid output: ________________________________________________________________Device UUID TYPE LABEL/dev/loop0 squashfs /dev/loop1 squashfs /dev/loop2 squashfs /dev/loop3 squashfs /dev/sda1 D422-C962 vfat /dev/sda2 b30147d2-e13f-4651-9263-60341c46de25 ext4 linux/dev/sdb1 0bac8e21-a536-4061-9986-2abea769d215 ext4 hdd/dev/sr0 2016-06-11-22-41-35-00 iso9660 MJRO1606================================ Mount points: =================================Device Mount_Point Type Options/dev/sr0 /bootmnt iso9660 (ro,noatime)=========================== sda2/boot/grub/grub.cfg: ===========================--------------------------------------------------------------------------------## DO NOT EDIT THIS FILE## It is automatically generated by grub-mkconfig using templates# from /etc/grub.d and settings from /etc/default/grub#### BEGIN /etc/grub.d/00_header ###insmod part_gptinsmod part_msdosif [ -s $prefix/grubenv ]; then load_envfiif [ ${next_entry} ] ; then set default=${next_entry} set next_entry= save_env next_entry set boot_once=trueelse set default=${saved_entry}fiif [ x${feature_menuentry_id} = xy ]; then menuentry_id_option=--idelse menuentry_id_option=fiexport menuentry_id_optionif [ ${prev_saved_entry} ]; then set saved_entry=${prev_saved_entry} save_env saved_entry set prev_saved_entry= save_env prev_saved_entry set boot_once=truefifunction savedefault { if [ -z ${boot_once} ]; then saved_entry=${chosen} save_env saved_entry fi}function load_video { if [ x$feature_all_video_module = xy ]; then insmod all_video else insmod efi_gop insmod efi_uga insmod ieee1275_fb insmod vbe insmod vga insmod video_bochs insmod video_cirrus fi}set menu_color_normal=light-gray/blackset menu_color_highlight=green/blackif [ x$feature_default_font_path = xy ] ; then font=unicodeelseinsmod part_gptinsmod ext2set root='hd0,gpt2'if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2 b30147d2-e13f-4651-9263-60341c46de25else search --no-floppy --fs-uuid --set=root b30147d2-e13f-4651-9263-60341c46de25fi font=/usr/share/grub/unicode.pf2fiif loadfont $font ; then set gfxmode=auto load_video insmod gfxterm set locale_dir=$prefix/locale set lang=en_US insmod gettextfiterminal_input consoleterminal_output gfxterminsmod part_gptinsmod ext2set root='hd0,gpt2'if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2 b30147d2-e13f-4651-9263-60341c46de25else search --no-floppy --fs-uuid --set=root b30147d2-e13f-4651-9263-60341c46de25fiinsmod pngbackground_image -m stretch /usr/share/grub/background.pngif [ x$feature_timeout_style = xy ] ; then set timeout_style=menu set timeout=5# Fallback normal timeout code in case the timeout_style feature is# unavailable.else set timeout=5fi### END /etc/grub.d/00_header ###### BEGIN /etc/grub.d/10_linux ###menuentry 'Manjaro Linux' --class manjaro --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-b30147d2-e13f-4651-9263-60341c46de25' { savedefault load_video set gfxpayload=keep insmod gzio insmod part_gpt insmod ext2 set root='hd0,gpt2' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2 b30147d2-e13f-4651-9263-60341c46de25 else search --no-floppy --fs-uuid --set=root b30147d2-e13f-4651-9263-60341c46de25 fi echo 'Loading Linux 4.4.13-1-MANJARO x64 ...' linux /boot/vmlinuz-4.4-x86_64 root=UUID=b30147d2-e13f-4651-9263-60341c46de25 rw quiet splash echo 'Loading initial ramdisk ...' initrd /boot/intel-ucode.img /boot/initramfs-4.4-x86_64.img}submenu 'Advanced options for Manjaro Linux' $menuentry_id_option 'gnulinux-advanced-b30147d2-e13f-4651-9263-60341c46de25' { menuentry 'Manjaro Linux (Kernel: 4.4.13-1-MANJARO x64)' --class manjaro --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-4.4.13-1-MANJARO x64-advanced-b30147d2-e13f-4651-9263-60341c46de25' { savedefault load_video set gfxpayload=keep insmod gzio insmod part_gpt insmod ext2 set root='hd0,gpt2' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2 b30147d2-e13f-4651-9263-60341c46de25 else search --no-floppy --fs-uuid --set=root b30147d2-e13f-4651-9263-60341c46de25 fi echo 'Loading Linux 4.4.13-1-MANJARO x64 ...' linux /boot/vmlinuz-4.4-x86_64 root=UUID=b30147d2-e13f-4651-9263-60341c46de25 rw quiet splash echo 'Loading initial ramdisk ...' initrd /boot/intel-ucode.img /boot/initramfs-4.4-x86_64.img } menuentry 'Manjaro Linux (Kernel: 4.4.13-1-MANJARO x64 - fallback initramfs)' --class manjaro --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-4.4.13-1-MANJARO x64-fallback-b30147d2-e13f-4651-9263-60341c46de25' { load_video set gfxpayload=keep insmod gzio insmod part_gpt insmod ext2 set root='hd0,gpt2' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2 b30147d2-e13f-4651-9263-60341c46de25 else search --no-floppy --fs-uuid --set=root b30147d2-e13f-4651-9263-60341c46de25 fi echo 'Loading Linux 4.4.13-1-MANJARO x64 ...' linux /boot/vmlinuz-4.4-x86_64 root=UUID=b30147d2-e13f-4651-9263-60341c46de25 rw quiet splash echo 'Loading initial ramdisk ...' initrd /boot/intel-ucode.img /boot/initramfs-4.4-x86_64-fallback.img }}### END /etc/grub.d/10_linux ###### BEGIN /etc/grub.d/20_linux_xen ###### END /etc/grub.d/20_linux_xen ###### BEGIN /etc/grub.d/30_os-prober ###### END /etc/grub.d/30_os-prober ###### BEGIN /etc/grub.d/40_custom #### This file provides an easy way to add custom menu entries. Simply type the# menu entries you want to add after this comment. Be careful not to change# the 'exec tail' line above.### END /etc/grub.d/40_custom ###### BEGIN /etc/grub.d/41_custom ###if [ -f ${config_directory}/custom.cfg ]; then source ${config_directory}/custom.cfgelif [ -z ${config_directory} -a -f $prefix/custom.cfg ]; then source $prefix/custom.cfg;fi### END /etc/grub.d/41_custom ###### BEGIN /etc/grub.d/60_memtest86+ ###if [ ${grub_platform} == pc ]; then menuentry Memory Tester (memtest86+) --class memtest86 --class gnu --class tool { search --fs-uuid --no-floppy --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2 b30147d2-e13f-4651-9263-60341c46de25 linux16 /boot/memtest86+/memtest.bin }fi### END /etc/grub.d/60_memtest86+ ###--------------------------------------------------------------------------------=============================== sda2/etc/fstab: ================================--------------------------------------------------------------------------------# /etc/fstab: static file system information.## Use 'blkid' to print the universally unique identifier for a device; this may# be used with UUID= as a more robust way to name devices that works even if# disks are added and removed. See fstab(5).## <file system> <mount point> <type> <options> <dump> <pass>UUID=0bac8e21-a536-4061-9986-2abea769d215 /hdd ext4 defaults,noatime 0 2UUID=b30147d2-e13f-4651-9263-60341c46de25 / ext4 defaults,noatime,discard 0 1UUID=7D0D-278F /boot/efi vfat defaults,noatime 0 2tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0--------------------------------------------------------------------------------======================= sda2/boot/syslinux/syslinux.cfg: =======================--------------------------------------------------------------------------------# Config file for Syslinux -# /boot/syslinux/syslinux.cfg## Comboot modules:# * menu.c32 - provides a text menu# * vesamenu.c32 - provides a graphical menu# * chain.c32 - chainload MBRs, partition boot sectors, Windows bootloaders# * hdt.c32 - hardware detection tool# * reboot.c32 - reboots the system## To Use: Copy the respective files from /usr/lib/syslinux to /boot/syslinux.# If /usr and /boot are on the same file system, symlink the files instead# of copying them.## If you do not use a menu, a 'boot:' prompt will be shown and the system# will boot automatically after 5 seconds.## Please review the wiki: https://wiki.archlinux.org/index.php/Syslinux# The wiki provides further configuration examplesDEFAULT archPROMPT 0 # Set to 1 if you always want to display the boot: promptTIMEOUT 50# You can create syslinux keymaps with the keytab-lilo tool#KBDMAP de.ktl# Menu Configuration# Either menu.c32 or vesamenu32.c32 must be copied to /boot/syslinuxUI menu.c32#UI vesamenu.c32# Refer to http://syslinux.zytor.com/wiki/index.php/Doc/menuMENU TITLE Arch Linux#MENU BACKGROUND splash.pngMENU COLOR border 30;44 #40ffffff #a0000000 stdMENU COLOR title 1;36;44 #9033ccff #a0000000 stdMENU COLOR sel 7;37;40 #e0ffffff #20ffffff allMENU COLOR unsel 37;44 #50ffffff #a0000000 stdMENU COLOR help 37;40 #c0ffffff #a0000000 stdMENU COLOR timeout_msg 37;40 #80ffffff #00000000 stdMENU COLOR timeout 1;37;40 #c0ffffff #00000000 stdMENU COLOR msg07 37;40 #90ffffff #a0000000 stdMENU COLOR tabmsg 31;40 #30ffffff #00000000 std# boot sections follow## TIP: If you want a 1024x768 framebuffer, add vga=773 to your kernel line.##-*LABEL arch MENU LABEL Arch Linux LINUX ../vmlinuz-linux APPEND root=/dev/sda3 rw INITRD ../initramfs-linux.imgLABEL archfallback MENU LABEL Arch Linux Fallback LINUX ../vmlinuz-linux APPEND root=/dev/sda3 rw INITRD ../initramfs-linux-fallback.img#LABEL windows# MENU LABEL Windows# COM32 chain.c32# APPEND hd0 1LABEL hdt MENU LABEL HDT (Hardware Detection Tool) COM32 hdt.c32LABEL reboot MENU LABEL Reboot COM32 reboot.c32LABEL poweroff MENU LABEL Poweroff COM32 poweroff.c32--------------------------------------------------------------------------------=================== sda2: Location of files loaded by Grub: ==================== GiB - GB File Fragment(s)================= sda2: Location of files loaded by Syslinux: ================== GiB - GB File Fragment(s)=============================== StdErr Messages: ===============================cat: /tmp/BootInfo-NjjdvYuk/Tmp_Log: No such file or directorycat: /tmp/BootInfo-NjjdvYuk/Tmp_Log: No such file or directorymdadm: No arrays found in config file or automaticallyand>>> ls -R /boot/efils -R /boot/efi/boot/efi:EFI/boot/efi/EFI:manjaro/boot/efi/EFI/manjaro:grubx64.efi
No bootable medium after installing grub on laptop Acer Aspire
boot;grub;manjaro
null
_unix.312864
While installing Ubuntu 16.04 I decided to take the option of encrypting my home directory. I also use ssh key-only authorization, as password logins are disabled for security.I was able to solve the not being able to log in because .ssh/authorized_keys issue using this: https://stephen.rees-carter.net/thought/encrypted-home-directories-ssh-key-authentication. In summary:sudo vim ~/.profileand then enteringecryptfs-mount-privatecd /home/usernameBut now, X11 forwarding over ssh is broken. It appears the MMC (MIT Magic Cookie) .Xauthority file is not making it into the un-encrypted home directory.
Encrypted Home Directory and SSH (Key-Only-Authentication) breaks X11 forwarding
ssh;x11;sshd;ecryptfs;xforwarding
null
_unix.143709
I find the following way to print line from fileIn this example we want to print the first line from the hosts file sed -n '1,1p' /etc/hosts127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4But how to do the same with parameters inside the sed commandFor exampleLine_number=1sed -n ' $Line_number,$Line_numberp' /etc/hosts sed: -e expression #1, char 4: extra characters after commandwhat is wrong in my sed syntax?
Sed + how to set parameters in sed command in order to display lines from text file
linux;sed;awk;ksh
Let your shell expand the variable by using instead of '.Example:victor@pyfg:~$ line_number=2victor@pyfg:~$ sed -n ${line_number},${line_number}p /etc/hosts1.2.3.4 row-2Since you're only printing a single row, you can just to it like this also:victor@pyfg:~$ sed -n ${line_number}p /etc/hosts1.2.3.4 row-2
_webapps.103201
I have a data source with multiple cells that contain 1 or sometimes more variables (separated by comma). I have some basic data in the first few columns that I would like to be present in each row (Salutation and name in the example), but I would like to make a new row for each variable in each multi-line cell. Also, for each column that has cells with comma separated variables, there's an adjacent label (in this case Label 1 & label 2) I'd like to keep those.Best case, I'd really like the data to look like this, with all the empty spaces gone. I've found scripts that work to separate a multi-line cell into separate rows keeping adjacent data. However, I've tried & tried, but I cannot figure out how to edit these scripts so they work for a data source with multiple multi line/variable cells. Help?
Google Scripts: Split multiple multi-line cells into separate rows keeping adjacent data
google spreadsheets;google apps script
null
_cs.76305
I am training a Variational Autoencoder (type of convolutional neural network), and have been plotting cost over time. The result is a noisy curve, shown here:I would like to write a function that gives the probability that the cost function has bottomed out, i.e. that its slope going into the future is zero. Due to the noise, I can't just take the derivative of the cost function, as it oscillates stochastically. I could take the derivative of the moving average of the cost function, but it would be unclear what window size to use, and regardless a single window size would be useful for only part of the line (the noise tends to increase over time).Is there some mathematical function/theorem I can use to take the local noise of the curve into account, and output a range/distribution of probable slopes? I would imagine the output being something like a histogram with the most likely slope at the middle and increasingly less-likely slopes off on the sides.
Given a Noisy Curve, Write a Function to Output Likely Slopes
optimization;neural networks;approximation;randomness
A moving window (with some reasonable window size) is probably hard to beat. I don't know of any parameter-less solution. Another possible approach could be to estimate the slope of the last 10% of the data, and compare this to some threshold. (So, the 1000th data point uses the average of points 900-1000. The 2000th data point uses the average of points 1800-2000. And so on.) This way, if it does flatten out, then if you continue for another 10% longer, you'll reach a point where the last 10% is all flat and the procedure will likely terminate. This may do 10% more iterations than necessary, but that might be acceptable given that in return you get a procedure that doesn't require a fixed window size.However, choosing a threshold might be a bit tricky. I'm not sure how to do that in a reasonable way.Given a bunch of data points, you can compute a least-squares fit for the regression line through those points, and find an estimate of the slope of that line. You can also compute a confidence interval for that slope. This will give you a range of plausible slopes.
_webmaster.105765
We had more than 500 pages indexed, we are a relatively new site but I think we have good content so Google was ok with our pages.Most of this pages were profiles and had a url structure like /place/place/workOne of our engineers changed the url structure and with that, updated the sitemap.The old url's starting throwing 404 because he didn't put any 301 redirection to the new ones and Google was not happy at all about this.Google de inxeded most of the pages and now we have only 75 indexed and 10 of them are profiles.This engineer was obviously at fault, but 2 weeks have passed and our indexed pages are still 75.Any tip on this? We have put a lot of effort for this pages to be seo friendly but it seems google dont trust us anymore :(Thanks!
Accident with a lot of indexed pages - Google is not happy
seo;sitemap;indexing;negative seo
null
_unix.244502
I'm running file against a wallet.dat file (A file that Bitcoin keeps its private keys in) and even though there doesn't seem to be any identifiable header or string, file can still tell that it's a Berkley DB file, even if I cut it down to 16 bytes.I know that file was applying some sort of rule or searching for some sequence to identify it. I want to know what the rule it's applying here is, so that I can duplicate it in my own program.
How did file identify this particular file?
file command
Grab the source of the file command. Most if not all open sources unices use this one. The file command comes with the magic database, named after the magic numbers that it describes. (This database is also installed on your live system, but in a compiled form.) Look for the file that contains the description text that you see:grep 'Berkeley DB' magic/Magdir/*The magic man page describes the format of the file. The trigger lines for Berkeley DB are0 long 0x00061561 Berkeley DB0 belong 0x00061561 Berkeley DB12 long 0x00061561 Berkeley DB12 belong 0x00061561 Berkeley DB12 lelong 0x00061561 Berkeley DB12 long 0x00053162 Berkeley DB12 belong 0x00053162 Berkeley DB12 lelong 0x00053162 Berkeley DB12 long 0x00042253 Berkeley DB12 belong 0x00042253 Berkeley DB12 lelong 0x00042253 Berkeley DB12 long 0x00040988 Berkeley DB12 belong 0x00040988 Berkeley DB 12 lelong 0x00040988 Berkeley DBThe first column specifies the offset at which a certain byte sequence is to be found. The third column contains the byte sequence. The second column describes the type of byte sequence: long means 4 bytes in the platform's endianness; lelong and belong mean 4 bytes in little-endian and big-endian order respectively.Rather than replicate the rules, you may want to call the file utility; it's specified by POSIX, but the formats that it recognizes and the descriptions that it outputs aren't. Alternatively, you can link to libmagic and call the magic_file or magic_buffer function.