Programs & Examples On #Imagebrush

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

When I had this problem, I had literally just forgot to fill in a parameter value in the XAML of the code.

For some reason though, the exception would send me to the CS of the WPF program rather than the XAML. No idea why.

Change WPF window background image in C# code

img.UriSource = new Uri("pack://application:,,,/images/" + fileName, UriKind.Absolute);

Pan & Zoom Image

The way I solved this problem was to place the image within a Border with it's ClipToBounds property set to True. The RenderTransformOrigin on the image is then set to 0.5,0.5 so the image will start zooming on the center of the image. The RenderTransform is also set to a TransformGroup containing a ScaleTransform and a TranslateTransform.

I then handled the MouseWheel event on the image to implement zooming

private void image_MouseWheel(object sender, MouseWheelEventArgs e)
{
    var st = (ScaleTransform)image.RenderTransform;
    double zoom = e.Delta > 0 ? .2 : -.2;
    st.ScaleX += zoom;
    st.ScaleY += zoom;
}

To handle the panning the first thing I did was to handle the MouseLeftButtonDown event on the image, to capture the mouse and to record it's location, I also store the current value of the TranslateTransform, this what is updated to implement panning.

Point start;
Point origin;
private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    image.CaptureMouse();
    var tt = (TranslateTransform)((TransformGroup)image.RenderTransform)
        .Children.First(tr => tr is TranslateTransform);
    start = e.GetPosition(border);
    origin = new Point(tt.X, tt.Y);
}

Then I handled the MouseMove event to update the TranslateTransform.

private void image_MouseMove(object sender, MouseEventArgs e)
{
    if (image.IsMouseCaptured)
    {
        var tt = (TranslateTransform)((TransformGroup)image.RenderTransform)
            .Children.First(tr => tr is TranslateTransform);
        Vector v = start - e.GetPosition(border);
        tt.X = origin.X - v.X;
        tt.Y = origin.Y - v.Y;
    }
}

Finally don't forget to release the mouse capture.

private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    image.ReleaseMouseCapture();
}

As for the selection handles for resizing this can be accomplished using an adorner, check out this article for more information.

WPF Image Dynamically changing Image source during runtime

Try Stretch="UniformToFill" on the Image

iOS 7.0 No code signing identities found

Obviously this issue has different causes. :)

For my case, my account log in expired... I solved it by simply:

XCode -> Preferences -> Account -> Apple IDs -> Select the related ID and renew the log in...

Hope this helps!

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

There second method will be many times more effective (mostly because of compilers inlining and boxing but still numbers are very expressive):

public static bool CheckObjectImpl(object o)
{
    return o != null;
}

public static bool CheckNullableImpl<T>(T? o) where T: struct
{
    return o.HasValue;
}

Benchmark test:

BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
  [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
  Clr    : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
  Core   : .NET Core 4.6.25009.03, 64bit RyuJIT


        Method |  Job | Runtime |       Mean |     Error |    StdDev |        Min |        Max |     Median | Rank |  Gen 0 | Allocated |
-------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
   CheckObject |  Clr |     Clr | 80.6416 ns | 1.1983 ns | 1.0622 ns | 79.5528 ns | 83.0417 ns | 80.1797 ns |    3 | 0.0060 |      24 B |
 CheckNullable |  Clr |     Clr |  0.0029 ns | 0.0088 ns | 0.0082 ns |  0.0000 ns |  0.0315 ns |  0.0000 ns |    1 |      - |       0 B |
   CheckObject | Core |    Core | 77.2614 ns | 0.5703 ns | 0.4763 ns | 76.4205 ns | 77.9400 ns | 77.3586 ns |    2 | 0.0060 |      24 B |
 CheckNullable | Core |    Core |  0.0007 ns | 0.0021 ns | 0.0016 ns |  0.0000 ns |  0.0054 ns |  0.0000 ns |    1 |      - |       0 B |

Benchmark code:

public class BenchmarkNullableCheck
{
    static int? x = (new Random()).Next();

    public static bool CheckObjectImpl(object o)
    {
        return o != null;
    }

    public static bool CheckNullableImpl<T>(T? o) where T: struct
    {
        return o.HasValue;
    }

    [Benchmark]
    public bool CheckObject()
    {
        return CheckObjectImpl(x);
    }

    [Benchmark]
    public bool CheckNullable()
    {
        return CheckNullableImpl(x);
    }
}

https://github.com/dotnet/BenchmarkDotNet was used

So if you have an option (e.g. writing custom serializers) to process Nullable in different pipeline than object - and use their specific properties - do it and use Nullable specific properties. So from consistent thinking point of view HasValue should be preferred. Consistent thinking can help you to write better code do not spending too much time in details.

PS. People say that advice "prefer HasValue because of consistent thinking" is not related and useless. Can you predict the performance of this?

public static bool CheckNullableGenericImpl<T>(T? t) where T: struct
{
    return t != null; // or t.HasValue?
}

PPS People continue minus, seems nobody tries to predict performance of CheckNullableGenericImpl. I will tell you: there compiler will not help you replacing !=null with HasValue. HasValue should be used directly if you are interested in performance.

JUNIT testing void methods

If it is possible in your case, you could make your methods method1(arg1) ... method7() protected instead of private so they could be accesible from test class within the same package. Then you can simply test all theese methods separately.

Automatically deleting related rows in Laravel (Eloquent ORM)

I would iterate through the collection detaching everything before deleting the object itself.

here's an example:

try {
        $user = User::findOrFail($id);
        if ($user->has('photos')) {
            foreach ($user->photos as $photo) {

                $user->photos()->detach($photo);
            }
        }
        $user->delete();
        return 'User deleted';
    } catch (Exception $e) {
        dd($e);
    }

I know it is not automatic but it is very simple.

Another simple approach would be to provide the model with a method. Like this:

public function detach(){
       try {
            
            if ($this->has('photos')) {
                foreach ($this->photos as $photo) {
    
                    $this->photos()->detach($photo);
                }
            }
           
        } catch (Exception $e) {
            dd($e);
        }
}

Then you can simply call this where you need:

$user->detach();
$user->delete();

Date difference in years using C#

Use:

int Years(DateTime start, DateTime end)
{
    return (end.Year - start.Year - 1) +
        (((end.Month > start.Month) ||
        ((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0);
}

Is there a decorator to simply cache function return values?

DISCLAIMER: I'm the author of kids.cache.

You should check kids.cache, it provides a @cache decorator that works on python 2 and python 3. No dependencies, ~100 lines of code. It's very straightforward to use, for instance, with your code in mind, you could use it like this:

pip install kids.cache

Then

from kids.cache import cache
...
class MyClass(object):
    ...
    @cache            # <-- That's all you need to do
    @property
    def name(self):
        return 1 + 1  # supposedly expensive calculation

Or you could put the @cache decorator after the @property (same result).

Using cache on a property is called lazy evaluation, kids.cache can do much more (it works on function with any arguments, properties, any type of methods, and even classes...). For advanced users, kids.cache supports cachetools which provides fancy cache stores to python 2 and python 3 (LRU, LFU, TTL, RR cache).

IMPORTANT NOTE: the default cache store of kids.cache is a standard dict, which is not recommended for long running program with ever different queries as it would lead to an ever growing caching store. For this usage you can plugin other cache stores using for instance (@cache(use=cachetools.LRUCache(maxsize=2)) to decorate your function/property/class/method...)

Casting string to enum

.NET 4.0+ has a generic Enum.TryParse

ContentEnum content;
Enum.TryParse(fileContentMessage, out content);

How can I print message in Makefile?

$(info your_text) : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text) : Fatal Error. This will stop the execution.

How to create a shortcut using PowerShell

I don't know any native cmdlet in powershell but you can use com object instead:

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()

you can create a powershell script save as set-shortcut.ps1 in your $pwd

param ( [string]$SourceExe, [string]$DestinationPath )

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()

and call it like this

Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"

If you want to pass arguments to the target exe, it can be done by:

#Set the additional parameters for the shortcut  
$Shortcut.Arguments = "/argument=value"  

before $Shortcut.Save().

For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.

param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()

Making Maven run all tests, even when some fail

I just found the "-fae" parameter, which causes Maven to run all tests and not stop on failure.

If using maven, usually you put log4j.properties under java or resources?

When putting resource files in another location is not the best solution you can use:

<build>
  <resources>
    <resource>
      <directory>src/main/java</directory>
      <excludes>
        <exclude>**/*.java</exclude>
      </excludes>
    </resource>
  </resources>
<build>

For example when resources files (e.g. jaxb.properties) goes deep inside packages along with Java classes.

This IP, site or mobile application is not authorized to use this API key

Also the corresponding API should be enabled for the given project

https://console.developers.google.com/apis/library?project=projectnamehere

How to clear all <div>sā€™ contents inside a parent <div>?

$('#div_id').empty();

or

$('.div_class').empty();

Works Fine to remove contents inside a div

Correct way to use get_or_create?

get_or_create returns a tuple.

customer.source, created = Source.objects.get_or_create(name="Website")

What is the best way to prevent session hijacking?

// Collect this information on every request
$aip = $_SERVER['REMOTE_ADDR'];
$bip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$agent = $_SERVER['HTTP_USER_AGENT'];
session_start();

// Do this each time the user successfully logs in.
$_SESSION['ident'] = hash("sha256", $aip . $bip . $agent);

// Do this every time the client makes a request to the server, after authenticating
$ident = hash("sha256", $aip . $bip . $agent);
if ($ident != $_SESSION['ident'])
{
    end_session();
    header("Location: login.php");
    // add some fancy pants GET/POST var headers for login.php, that lets you
    // know in the login page to notify the user of why they're being challenged
    // for login again, etc.
}

What this does is capture 'contextual' information about the user's session, pieces of information which should not change during the life of a single session. A user isn't going to be at a computer in the US and in China at the same time, right? So if the IP address changes suddenly within the same session that strongly implies a session hijacking attempt, so you secure the session by ending the session and forcing the user to re-authenticate. This thwarts the hack attempt, the attacker is also forced to login instead of gaining access to the session. Notify the user of the attempt (ajax it up a bit), and vola, Slightly annoyed+informed user and their session/information is protected.

We throw in User Agent and X-FORWARDED-FOR to do our best to capture uniqueness of a session for systems behind proxies/networks. You may be able to use more information then that, feel free to be creative.

It's not 100%, but it's pretty damn effective.

There's more you can do to protect sessions, expire them, when a user leaves a website and comes back force them to login again maybe. You can detect a user leaving and coming back by capturing a blank HTTP_REFERER (domain was typed in the URL bar), or check if the value in the HTTP_REFERER equals your domain or not (the user clicked an external/crafted link to get to your site).

Expire sessions, don't let them remain valid indefinitely.

Don't rely on cookies, they can be stolen, it's one of the vectors of attack for session hijacking.

How to use confirm using sweet alert?

You need To use then() function, like this

swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!"
 }).then(
       function () { /*Your Code Here*/ },
       function () { return false; });

How do I set browser width and height in Selenium WebDriver?

Try something like this:

IWebDriver _driver = new FirefoxDriver();
_driver.Manage().Window.Position = new Point(0, 0);
_driver.Manage().Window.Size = new Size(1024, 768);

Not sure if it'll resize after being launched though, so maybe it's not what you want

How to check if spark dataframe is empty?

You can take advantage of the head() (or first()) functions to see if the DataFrame has a single row. If so, it is not empty.

Detecting superfluous #includes in C/C++?

To end this discussion: the c++ preprocessor is turing complete. It is a semantic property, whether an include is superfluous. Hence, it follows from Rice's theorem that it is undecidable whether an include is superfluous or not. There CAN'T be a program, that (always correctly) detects whether an include is superfluous.

Get folder name from full file path

Simply use Path.GetFileName

Here - Extract folder name from the full path of a folder:

string folderName = Path.GetFileName(@"c:\projects\root\wsdlproj\devlop\beta2\text");//Return "text"

Here is some extra - Extract folder name from the full path of a file:

string folderName = Path.GetFileName(Path.GetDirectoryName(@"c:\projects\root\wsdlproj\devlop\beta2\text\GTA.exe"));//Return "text"

How to read integer values from text file

I would use nearly the same way but with list as buffer for read integers:

static Object[] readFile(String fileName) {
    Scanner scanner = new Scanner(new File(fileName));
    List<Integer> tall = new ArrayList<Integer>();
    while (scanner.hasNextInt()) {
        tall.add(scanner.nextInt());
    }

    return tall.toArray();
}

Adding/removing items from a JavaScript object with jQuery

Splice is good, everyone explain splice so I didn't explain it. You can also use delete keyword in JavaScript, it's good. You can use $.grep also to manipulate this using jQuery.

The jQuery Way :

data.items = jQuery.grep(
                data.items, 
                function (item,index) { 
                  return item.id !=  "1"; 
                });

DELETE Way:

delete data.items[0]

For Adding PUSH is better the splice, because splice is heavy weighted function. Splice create a new array , if you have a huge size of array then it may be troublesome. delete is sometime useful, after delete if you look for the length of the array then there is no change in length there. So use it wisely.

How can I iterate over an enum?

You can also overload the increment/decrement operators for your enumerated type.

Use of exit() function

Try man exit.


Oh, and:

#include <stdlib.h>

int main(void) {
  /*  ...  */
  if (error_occured) {
    return (EXIT_FAILURE);
  }
  /*  ...  */
  return (EXIT_SUCCESS);
}

rotating axis labels in R

As Maciej Jonczyk mentioned, you may also need to increase margins

par(las=2)
par(mar=c(8,8,1,1)) # adjust as needed
plot(...)

Open a Web Page in a Windows Batch FIle

You can use the start command to do much the same thing as ShellExecute. For example

 start "" http://www.stackoverflow.com

This will launch whatever browser is the default browser, so won't necessarily launch Internet Explorer.

How to fix Error: listen EADDRINUSE while using nodejs?

Your application is already running on that port 8080 . Use this code to kill the port and run your code again

sudo lsof -t -i tcp:8080 | xargs kill -9

Emulator in Android Studio doesn't start

enter image description here

Wipe data of AVD like that picture and run your program. it's work for me.

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

If you are using Eclipse Neon, try this:

1) Add the maven plugin in the properties section of the POM:

<properties>
    <java.version>1.8</java.version>
    <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>

2) Force update of project snapshot by right clicking on Project

Maven -> Update Project -> Select your Project -> Tick on the 'Force Update of Snapshots/Releases' option -> OK

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

I'm running JMeter 2.8 (Windows 7) and received a message similar to that in the original post:

C:\>jmeter
Error: Unable to access jarfile C:\local\software\jMeter\apache-jmeter-2.8\binApacheJMeter.jar
errorlevel=1
Press any key to continue . . .

I'd created a Windows environment variable JMETER_BIN and set it to the JMeter path which I could see contained ApacheJMeter.jar (so it wasn't a question that the jar was missing).

I should have noticed at the time this portion of the error: "binApacheJMeter.jar"

When I went to the jmeter.bat file to troubleshoot, I noticed this line:

%JM_START% %JM_LAUNCH% %ARGS% %JVM_ARGS% -jar "%JMETER_BIN%ApacheJMeter.jar" %JMETER_CMD_LINE_ARGS%

and that caused me to revisit the "binApacheJMeter.jar" portion of the error.

What was happening was that the batch file was requiring a trailing slash on the end of the path in the JMETER_BIN environment variable to correctly specify the location of the .jar.

Once I corrected my environment variable, adding the trailing slash, all was wonderful.

YMMV, but this worked for me.

Variable name as a string in Javascript

var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];

This isn't able to be made into a function as it returns the name of the function's variable.

// THIS DOESN'T WORK
function getVarName(v) {
    return Object.keys({v})[0];
}
// Returns "v"

Edit: Thanks to @Madeo for pointing out how to make this into a function.

function debugVar(varObj) {
    var varName = Object.keys(varObj)[0];
    console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}

You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.

Enable the display of line numbers in Visual Studio

Tools -> Options -> Show All Settings -> Text Editor -> All Languages -> Line Numbers

Environment variable substitution in sed

Dealing with VARIABLES within sed

[root@gislab00207 ldom]# echo domainname: None > /tmp/1.txt

[root@gislab00207 ldom]# cat /tmp/1.txt

domainname: None

[root@gislab00207 ldom]# echo ${DOMAIN_NAME}

dcsw-79-98vm.us.oracle.com

[root@gislab00207 ldom]# cat /tmp/1.txt | sed -e 's/domainname: None/domainname: ${DOMAIN_NAME}/g'

 --- Below is the result -- very funny.

domainname: ${DOMAIN_NAME}

 --- You need to single quote your variable like this ... 

[root@gislab00207 ldom]# cat /tmp/1.txt | sed -e 's/domainname: None/domainname: '${DOMAIN_NAME}'/g'


--- The right result is below 

domainname: dcsw-79-98vm.us.oracle.com

How do I return JSON without using a template in Django?

It looks like the Django REST framework uses the HTTP accept header in a Request in order to automatically determine which renderer to use:

http://www.django-rest-framework.org/api-guide/renderers/

Using the HTTP accept header may provide an alternative source for your "if something".

simple custom event

You haven't created an event. To do that write:

public event EventHandler<Progress> Progress;

Then, you can call Progress from within the class where it was declared like normal function or delegate:

Progress(this, new Progress("some status"));

So, if you want to report progress in TestClass, the event should be in there too and it should be also static. You can the subscribe to it from your form like this:

TestClass.Progress += SetStatus;

Also, you should probably rename Progress to ProgressEventArgs, so that it's clear what it is.

Proper MIME type for OTF fonts

Since Feb 2017 RFC 8081 groups all MIME types for fonts under the top level font media type. The older MIME types from my original posting are now listed as deprecated.

Font types as listed by IANA are now:

Other non-standard font formats are left as are:


[Outdated Original Post]

As there's still a lot of confusion on the web about MIME types for web fonts, I thought I'd give a current answer, complete with effective dates, and supporting links to IANA and the W3C.

Here are the official MIME types for Web Fonts:

Note there is a movement to change all the above to MIME types of font/XXX, as backed by the W3C in its proposal for WOFF v2. This is being tracked by the Internet Engineering Task Force (IETF) under The font Top Level Type and in February 2017 was approved RFC status (see RFC 8081) so it may all change yet!

While on the topic of web servers, it's worth mentioning that HTTP responses may gzip (or otherwise compress) all the above font formats except .woff & .woff2 which are already heavily compressed.

I say more in MIME Types for Web Fonts with (Fantom) BedSheet.

Query to count the number of tables I have in MySQL

To count number of tables just do this:

USE your_db_name;    -- set database
SHOW TABLES;         -- tables lists
SELECT FOUND_ROWS(); -- number of tables

Sometimes easy things will do the work.

Constraint Layout Vertical Align Center

You can easily center multiple things by creating a chain. It works both vertically and horizontally

Link to official documentation about chains

Edit to answer comment :

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
    <TextView
        android:id="@+id/first_score"
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:text="10"
        app:layout_constraintEnd_toStartOf="@+id/second_score"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/second_score"
        app:layout_constraintBottom_toTopOf="@+id/subtitle"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintVertical_chainStyle="packed"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subtitle"
        app:layout_constraintTop_toBottomOf="@+id/first_score"
        app:layout_constraintBottom_toBottomOf="@+id/second_score"
        app:layout_constraintStart_toStartOf="@id/first_score"
        app:layout_constraintEnd_toEndOf="@id/first_score"
        />
    <TextView
        android:id="@+id/second_score"
        android:layout_width="60dp"
        android:layout_height="120sp"
        android:text="243"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/thrid_score"
        app:layout_constraintStart_toEndOf="@id/first_score"
        app:layout_constraintTop_toTopOf="parent"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/thrid_score"
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:text="3200"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/second_score"
        app:layout_constraintTop_toTopOf="@id/second_score"
        app:layout_constraintBottom_toBottomOf="@id/second_score"
        android:gravity="center"
        />
</android.support.constraint.ConstraintLayout>

This code gives this result

You have the horizontal chain : first_score <=> second_score <=> third_score. second_score is centered vertically. The other scores are centered vertically according to it.

You can definitely create a vertical chain first_score <=> subtitle and center it according to second_score

How to Clear Console in Java?

Use the following code:


System.out.println("\f");

'\f' is an escape sequence which represents FormFeed. This is what I have used in my projects to clear the console. This is simpler than the other codes, I guess.

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

You can define foreign key by:

public class Parent
{
   public int Id { get; set; }
   public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
   public int Id { get; set; }
   // This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
   public int ParentId { get; set; } 
   public virtual Parent Parent { get; set; }
}

Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.

If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation

Data annotation:

// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }

Fluent API:

modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithMany(p => p.Childs)
            .HasForeignKey(c => c.ParentId);

Other types of constraints can be enforced by data annotations and model validation.

Edit:

You will get an exception if you don't set ParentId. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.

Is there an eval() function in Java?

There are very few real use cases in which being able to evaluate a String as a fragment of Java code is necessary or desirable. That is, asking how to do this is really an XY problem: you actually have a different problem, which can be solved a different way.

First ask yourself, where did this String that you wish to evaluate come from? Did another part of your program generate it, or was it input provided by the user?

  • Another part of my program generated it: so, you want one part of your program to decide the kind of operation to perform, but not perform the operation, and a second part that performs the chosen operation. Instead of generating and then evaluating a String, use the Strategy, Command or Builder design pattern, as appropriate for your particular case.

  • It is user input: the user could input anything, including commands that, when executed, could cause your program to misbehave, crash, expose information that should be secret, damage persistent information (such as the content of a database), and other such nastiness. The only way to prevent that would be to parse the String yourself, check it was not malicious, and then evaluate it. But parsing it yourself is much of the work that the requested evalfunction would do, so you have saved yourself nothing. Worse still, checking that arbitrary Java was not malicious is impossible, because checking that is the halting problem.

  • It is user input, but the syntax and semantics of permitted text to evaluate is greatly restricted: No general purpose facility can easily implement a general purpose parser and evaluator for whatever restricted syntax and semantics you have chosen. What you need to do is implement a parser and evaluator for your chosen syntax and semantics. If the task is simple, you could write a simple recursive-descent or finite-state-machine parser by hand. If the task is difficult, you could use a compiler-compiler (such as ANTLR) to do some of the work for you.

  • I just want to implement a desktop calculator!: A homework assignment, eh? If you could implement the evaluation of the input expression using a provided eval function, it would not be much of a homework assignment, would it? Your program would be three lines long. Your instructor probably expects you to write the code for a simple arithmetic parser/evaluator. There is well known algorithm, shunting-yard, which you might find useful.

Simple way to convert datarow array to datatable

DataTable dt = new DataTable();
foreach (DataRow dr in drResults)
{ 
    dt.ImportRow(dr);
}   

How can I run a html file from terminal?

For those like me, who have reached this thread because they want to serve an html file from linux terminal or want to view it using a terminal command, use these steps:-

1)If you want to view your html using a browser:-
Navigate to the directory containing the html file
If you have chrome installed, Use:-

google-chrome <filename>.html


                OR
Use:-

firefox <filename>.html

2)If you want to serve html file and view it using a browser
Navigate to the directory containing the html file
And Simply type the following on the Terminal:-

pushd <filename>.html; python3 -m http.server 9999; popd;


Then click the I.P. address 0.0.0.0:9999 OR localhost:9999 (Whatever is the result after executing the above commands). Or type on the terminal :-

firefox 0.0.0.0:9999


Using the second method, anyone else connected to the same network can also view your file by using the URL:- "0.0.0.0:9999"

Java HTTP Client Request with defined timeout

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

...

    // set the connection timeout value to 30 seconds (30000 milliseconds)
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
    client = new DefaultHttpClient(httpParams);

How can I query a value in SQL Server XML column

if your field name is Roles and table name is table1 you can use following to search

DECLARE @Role varchar(50);
SELECT * FROM table1
WHERE Roles.exist ('/root/role = sql:variable("@Role")') = 1

Why do this() and super() have to be the first statement in a constructor?

I totally agree, the restrictions are too strong. Using a static helper method (as Tom Hawtin - tackline suggested) or shoving all "pre-super() computations" into a single expression in the parameter is not always possible, e.g.:

class Sup {
    public Sup(final int x_) { 
        //cheap constructor 
    }
    public Sup(final Sup sup_) { 
        //expensive copy constructor 
    }
}

class Sub extends Sup {
    private int x;
    public Sub(final Sub aSub) {
        /* for aSub with aSub.x == 0, 
         * the expensive copy constructor is unnecessary:
         */

         /* if (aSub.x == 0) { 
          *    super(0);
          * } else {
          *    super(aSub);
          * } 
          * above gives error since if-construct before super() is not allowed.
          */

        /* super((aSub.x == 0) ? 0 : aSub); 
         * above gives error since the ?-operator's type is Object
         */

        super(aSub); // much slower :(  

        // further initialization of aSub
    }
}

Using an "object not yet constructed" exception, as Carson Myers suggested, would help, but checking this during each object construction would slow down execution. I would favor a Java compiler that makes a better differentiation (instead of inconsequently forbidding an if-statement but allowing the ?-operator within the parameter), even if this complicates the language spec.

Google Chrome redirecting localhost to https

This is not a solution, it's just a workaround.

  1. Click on your visual studio project (top level) in the solution explorer and go to the properties window.

  2. Change SSL Enabled to true. You will now see another port number as 'SSL URL' in the properties window.

  3. Now, when you run your application (or view in browser), you have to manually change the port number to the SSL port number in the address bar.

Now it works fine as a SSL link

Filter data.frame rows by a logical condition

we can use data.table library

  library(data.table)
  expr <- data.table(expr)
  expr[cell_type == "hesc"]
  expr[cell_type %in% c("hesc","fibroblast")]

or filter using %like% operator for pattern matching

 expr[cell_type %like% "hesc"|cell_type %like% "fibroblast"]

Print to the same line and not a new line?

If you are using Spyder, the lines just print continuously with all the previous solutions. A way to avoid that is using:

for i in range(1000):
    print('\r' + str(round(i/len(df)*100,1)) + '% complete', end='')
    sys.stdout.flush()

How to connect Robomongo to MongoDB

Note: Commenting out bind_ip can make your system vulnerable to security flaws. Please see Security Checklist. It is a better idea to add more IP addresses than to open up your system to everything.

You need to edit your /etc/mongod.conf file's bind_ip variable to include the IP of the computer you're using, or eliminate it altogether.

I was able to connect using the following mongod.conf file. I commented out bind_ip and uncommented port.

# mongod.conf

# Where to store the data.

# Note: if you run MongoDB as a non-root user (recommended) you may
# need to create and set permissions for this directory manually.
# E.g., if the parent directory isn't mutable by the MongoDB user.

dbpath=/var/lib/mongodb

# Where to log
logpath=/var/log/mongodb/mongod.log

logappend=true

port = 27017

# Listen to local interface only. Comment out to listen on all
interfaces.

#bind_ip = 127.0.0.1


# Disables write-ahead journaling
# nojournal = true

# Enables periodic logging of CPU utilization and I/O wait
#cpu = true

# Turn on/off security.  Off is currently the default
#noauth = true

#auth = true

# Verbose logging output.
#verbose = true

# Inspect all client data for validity on receipt (useful for
# developing drivers)
#objcheck = true

# Enable db quota management
#quota = true

# Set oplogging level where n is
#   0=off (default)
#   1=W
#   2=R
#   3=both
#   7=W+some reads
#diaglog = 0

# Ignore query hints
#nohints = true

# Enable the HTTP interface (Defaults to port 28017).
#httpinterface = true

# Turns off server-side scripting.  This will result in greatly limited
# functionality
#noscripting = true

# Turns off table scans.  Any query that would do a table scan fails.
#notablescan = true

# Disable data file preallocation.
#noprealloc = true

# Specify .ns file size for new databases.
# nssize = <size>

# Replication Options
# In replicated MongoDB databases, specify the replica set name here
#replSet=setname

# Maximum size in megabytes for replication operation log
#oplogSize=1024

# Path to a key file storing authentication info for connections
# between replica set members
#keyFile=/path/to/keyfile

Don't forget to restart the mongod service before trying to connect:

service mongod restart

From Robomongo, I used the following connection settings:

Connection Tab:

  • Address: [VPS IP] : 27017

SSH Tab:

  • SSH Address: [VPS IP] : 22

  • SSH User Name: [Username for sudo enabled user]

  • SSH Auth Method: Password

  • User Password: Supersecret

How to remove all namespaces from XML with C#?

I tried the first few solutions and didn't work for me. Mainly the problem with attributes being removed like the other have already mentioned. I would say my approach is very similar to Jimmy by using the XElement constructors that taking object as parameters.

public static XElement RemoveAllNamespaces(this XElement element)
{
    return new XElement(element.Name.LocalName,
                        element.HasAttributes ? element.Attributes().Select(a => new XAttribute(a.Name.LocalName, a.Value)) : null,
                        element.HasElements ? element.Elements().Select(e => RemoveAllNamespaces(e)) : null,
                        element.Value);
}

Redirecting to URL in Flask

You have to return a redirect:

import os
from flask import Flask,redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("http://www.example.com", code=302)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

See the documentation on flask docs. The default value for code is 302 so code=302 can be omitted or replaced by other redirect code (one in 301, 302, 303, 305, and 307).

Best way to find os name and version in Unix/Linux platform

This work fine for all Linux environment.

#!/bin/sh
cat /etc/*-release

In Ubuntu:

$ cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=10.04
DISTRIB_CODENAME=lucid
DISTRIB_DESCRIPTION="Ubuntu 10.04.4 LTS"

or 12.04:

$ cat /etc/*-release

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.04
DISTRIB_CODENAME=precise
DISTRIB_DESCRIPTION="Ubuntu 12.04.4 LTS"
NAME="Ubuntu"
VERSION="12.04.4 LTS, Precise Pangolin"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu precise (12.04.4 LTS)"
VERSION_ID="12.04"

In RHEL:

$ cat /etc/*-release
Red Hat Enterprise Linux Server release 6.5 (Santiago)
Red Hat Enterprise Linux Server release 6.5 (Santiago)

Or Use this Script:

#!/bin/sh
# Detects which OS and if it is Linux then it will detect which Linux
# Distribution.

OS=`uname -s`
REV=`uname -r`
MACH=`uname -m`

GetVersionFromFile()
{
    VERSION=`cat $1 | tr "\n" ' ' | sed s/.*VERSION.*=\ // `
}

if [ "${OS}" = "SunOS" ] ; then
    OS=Solaris
    ARCH=`uname -p` 
    OSSTR="${OS} ${REV}(${ARCH} `uname -v`)"
elif [ "${OS}" = "AIX" ] ; then
    OSSTR="${OS} `oslevel` (`oslevel -r`)"
elif [ "${OS}" = "Linux" ] ; then
    KERNEL=`uname -r`
    if [ -f /etc/redhat-release ] ; then
        DIST='RedHat'
        PSUEDONAME=`cat /etc/redhat-release | sed s/.*\(// | sed s/\)//`
        REV=`cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//`
    elif [ -f /etc/SuSE-release ] ; then
        DIST=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
        REV=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
    elif [ -f /etc/mandrake-release ] ; then
        DIST='Mandrake'
        PSUEDONAME=`cat /etc/mandrake-release | sed s/.*\(// | sed s/\)//`
        REV=`cat /etc/mandrake-release | sed s/.*release\ // | sed s/\ .*//`
    elif [ -f /etc/debian_version ] ; then
        DIST="Debian `cat /etc/debian_version`"
        REV=""

    fi
    if [ -f /etc/UnitedLinux-release ] ; then
        DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
    fi

    OSSTR="${OS} ${DIST} ${REV}(${PSUEDONAME} ${KERNEL} ${MACH})"

fi

echo ${OSSTR}

Parsing JSON from XmlHttpRequest.responseJSON

Use nsIJSON if this is for a FF extension:

var req = new XMLHttpRequest;
req.overrideMimeType("application/json");
req.open('GET', BITLY_CREATE_API + encodeURIComponent(url) + BITLY_API_LOGIN, true);
var target = this;
req.onload = function() {target.parseJSON(req, url)};
req.send(null);

parseJSON: function(req, url) {
if (req.status == 200) {
  var jsonResponse = Components.classes["@mozilla.org/dom/json;1"]
      .createInstance(Components.interfaces.nsIJSON.decode(req.responseText);
  var bitlyUrl = jsonResponse.results[url].shortUrl;
}

For a webpage, just use JSON.parse instead of Components.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON.decode

Delete column from SQLite table

I've made a Python function where you enter the table and column to remove as arguments:

def removeColumn(table, column):
    columns = []
    for row in c.execute('PRAGMA table_info(' + table + ')'):
        columns.append(row[1])
    columns.remove(column)
    columns = str(columns)
    columns = columns.replace("[", "(")
    columns = columns.replace("]", ")")
    for i in ["\'", "(", ")"]:
        columns = columns.replace(i, "")
    c.execute('CREATE TABLE temptable AS SELECT ' + columns + ' FROM ' + table)
    c.execute('DROP TABLE ' + table)
    c.execute('ALTER TABLE temptable RENAME TO ' + table)
    conn.commit()

As per the info on Duda's and MeBigFatGuy's answers this won't work if there is a foreign key on the table, but this can be fixed with 2 lines of code (creating a new table and not just renaming the temporary table)

How to set a transparent background of JPanel?

Alternatively, consider The Glass Pane, discussed in the article How to Use Root Panes. You could draw your "Feature" content in the glass pane's paintComponent() method.

Addendum: Working with the GlassPaneDemo, I added an image:

//Set up the content pane, where the "main GUI" lives.
frame.add(changeButton, BorderLayout.SOUTH);
frame.add(new JLabel(new ImageIcon("img.jpg")), BorderLayout.CENTER);

and altered the glass pane's paintComponent() method:

protected void paintComponent(Graphics g) {
    if (point != null) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, 0.3f));
        g2d.setColor(Color.yellow);
        g2d.fillOval(point.x, point.y, 120, 60);
    }
}

enter image description here

As noted here, Swing components must honor the opaque property; in this variation, the ImageIcon completely fills the BorderLayout.CENTER of the frame's default layout.

What are database normal forms and can you give examples?

Here's a quick, admittedly butchered response, but in a sentence:

1NF : Your table is organized as an unordered set of data, and there are no repeating columns.

2NF: You don't repeat data in one column of your table because of another column.

3NF: Every column in your table relates only to your table's key -- you wouldn't have a column in a table that describes another column in your table which isn't the key.

For more detail, see wikipedia...

MaxLength Attribute not generating client-side validation attributes

I had this same problem and I was able to solve it by implementing the IValidatableObject interface in my view model.

public class RegisterViewModel : IValidatableObject
{
    /// <summary>
    /// Error message for Minimum password
    /// </summary>
    public static string PasswordLengthErrorMessage => $"The password must be at least {PasswordMinimumLength} characters";

    /// <summary>
    /// Minimum acceptable password length
    /// </summary>
    public const int PasswordMinimumLength = 8;

    /// <summary>
    /// Gets or sets the password provided by the user.
    /// </summary>
    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    /// <summary>
    /// Only need to validate the minimum length
    /// </summary>
    /// <param name="validationContext">ValidationContext, ignored</param>
    /// <returns>List of validation errors</returns>
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var errorList = new List<ValidationResult>();
        if ((Password?.Length ?? 0 ) < PasswordMinimumLength)
        {
            errorList.Add(new ValidationResult(PasswordLengthErrorMessage, new List<string>() {"Password"}));
        }
        return errorList;
    }
}

The markup in the Razor is then...

<div class="form-group">
    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password, new { @class = "form-control input-lg" }
    <div class="password-helper">Must contain: 8 characters, 1 upper-case, 1 lower-case
    </div>
    @Html.ValidationMessagesFor(m => m.Password, new { @class = "text-danger" })
</div>

This works really well. If I attempt to use [StringLength] instead then the rendered HTML is just not correct. The validation should render as:

<span class="text-danger field-validation-invalid field-validation-error" data-valmsg-for="Password" data-valmsg-replace="true"><span id="Password-error" class="">The Password should be a minimum of 8 characters long.</span></span>

With the StringLengthAttribute the rendered HTML shows as a ValidationSummary which is not correct. The funny thing is that when the validator fails the submit is still blocked!

How to percent-encode URL parameters in Python?

Python 2

From the docs:

urllib.quote(string[, safe])

Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted ā€” its default value is '/'

That means passing '' for safe will solve your first issue:

>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'

About the second issue, there is a bug report about it here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 like this:

>>> query = urllib.quote(u"MĆ¼ller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
MĆ¼ller

By the way have a look at urlencode

Python 3

The same, except replace urllib.quote with urllib.parse.quote.

Specify system property to Maven project

Is there a way ( I mean how do I ) set a system property in a maven project? I want to access a property from my test [...]

You can set system properties in the Maven Surefire Plugin configuration (this makes sense since tests are forked by default). From Using System Properties:

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <systemPropertyVariables>
            <propertyName>propertyValue</propertyName>
            <buildDirectory>${project.build.directory}</buildDirectory>
            [...]
          </systemPropertyVariables>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

and my webapp ( running locally )

Not sure what you mean here but I'll assume the webapp container is started by Maven. You can pass system properties on the command line using:

mvn -DargLine="-DpropertyName=propertyValue"

Update: Ok, got it now. For Jetty, you should also be able to set system properties in the Maven Jetty Plugin configuration. From Setting System Properties:

<project>
  ...
  <plugins>
    ...
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <configuration>
         ...
         <systemProperties>
            <systemProperty>
              <name>propertyName</name>
              <value>propertyValue</value>
            </systemProperty>
            ...
         </systemProperties>
        </configuration>
      </plugin>
  </plugins>
</project>

Can I scroll a ScrollView programmatically in Android?

I was using the Runnable with sv.fullScroll(View.FOCUS_DOWN); It works perfectly for the immediate problem, but that method makes ScrollView take the Focus from the entire screen, if you make that AutoScroll to happen every time, no EditText will be able to receive information from the user, my solution was use a different code under the runnable:

sv.scrollTo(0, sv.getBottom() + sv.getScrollY());

making the same without losing focus on important views

greetings.

Custom CSS Scrollbar for Firefox

As of now there is just two property for firefox scrollbar customization is available .

scrollbar-color & scrollbar width

scrollbar-color:red yellow; (track,thumb) scrollbar-width:5px;

HTML

<div class="demo">

css

.demo {
overflow-y:scroll;
}

.demo {
scrollbar-color:red yellow;
scrollbar-width:5px;
}

How to setup Tomcat server in Netbeans?

If TomCat is install. Perhaps it is not installed Java EE. Services-> plug-ins-> additional plug-ins-> in the search dial tomcat. and install the module java ee. then in the services, servers, add the tomcat server.

Update multiple rows in same query using PostgreSQL

For updating multiple rows in a single query, you can try this

UPDATE table_name
SET 
column_1 = CASE WHEN any_column = value and any_column = value THEN column_1_value end,
column_2 = CASE WHEN any_column = value and any_column = value THEN column_2_value end,
column_3 = CASE WHEN any_column = value and any_column = value THEN column_3_value end,
.
.
.
column_n = CASE WHEN any_column = value and any_column = value THEN column_n_value end

if you don't need additional condition then remove and part of this query

How do I compile the asm generated by GCC?

Yes, You can use gcc to compile your asm code. Use -c for compilation like this:

gcc -c file.S -o file.o

This will give object code file named file.o. To invoke linker perform following after above command:

gcc file.o -o file

Swap DIV position with CSS only

assuming both elements have 50% width, here is what i used:

css:

  .parent {
    width: 100%;
    display: flex;
  }  
  .child-1 {
    width: 50%;
    margin-right: -50%;
    margin-left: 50%;
    background: #ff0;
  }
  .child-2 {
    width: 50%;
    margin-right: 50%;
    margin-left: -50%;
    background: #0f0;
  }

html:

<div class="parent">
  <div class="child-1">child1</div>
  <div class="child-2">child2</div>
</div>

example: https://jsfiddle.net/gzveri/o6umhj53/

btw, this approach works for any 2 nearby elements in a long list of elements. For example I have a long list of elements with 2 items per row and I want each 3-rd and 4-th element in the list to be swapped, so that it renders elements in a chess style, then I use these rules:

  .parent > div:nth-child(4n+3) {
    margin-right: -50%;
    margin-left: 50%;
  }
  .parent > div:nth-child(4n+4) {
    margin-right: 50%;
    margin-left: -50%;
  }

How to overlay density plots in R?

That's how I do it in base (it's actually mentionned in the first answer comments but I'll show the full code here, including legend as I can not comment yet...)

First you need to get the info on the max values for the y axis from the density plots. So you need to actually compute the densities separately first

dta_A <- density(VarA, na.rm = TRUE)
dta_B <- density(VarB, na.rm = TRUE)

Then plot them according to the first answer and define min and max values for the y axis that you just got. (I set the min value to 0)

plot(dta_A, col = "blue", main = "2 densities on one plot"), 
     ylim = c(0, max(dta_A$y,dta_B$y)))  
lines(dta_B, col = "red")

Then add a legend to the top right corner

legend("topright", c("VarA","VarB"), lty = c(1,1), col = c("blue","red"))

Java 8 lambda get and remove element from list

I'm sure this will be an unpopular answer, but it works...

ProducerDTO[] p = new ProducerDTO[1];
producersProcedureActive
            .stream()
            .filter(producer -> producer.getPod().equals(pod))
            .findFirst()
            .ifPresent(producer -> {producersProcedureActive.remove(producer); p[0] = producer;}

p[0] will either hold the found element or be null.

The "trick" here is circumventing the "effectively final" problem by using an array reference that is effectively final, but setting its first element.

Logging in Scala

You should have a look at the scalax library : http://scalax.scalaforge.org/ In this library, there is a Logging trait, using sl4j as backend. By using this trait, you can log quite easily (just use the logger field in the class inheriting the trait).

What does !important mean in CSS?

!important is a part of CSS1.

Browsers supporting it: IE5.5+, Firefox 1+, Safari 3+, Chrome 1+.

It means, something like:

Use me, if there is nothing important else around!

Cant say it better.

int value under 10 convert to string two digit number

The accepted answer is good and fast:

i.ToString("00")

or

i.ToString("000")

If you need more complexity, String.Format is worth a try:

var str1 = "";
var str2 = "";
for (int i = 1; i < 100; i++)
{
    str1 = String.Format("{0:00}", i);
    str2 = String.Format("{0:000}", i);
}

For the i = 10 case:

str1: "10"
str2: "010"

I use this, for example, to clear the text on particular Label Controls on my form by name:

private void EmptyLabelArray()
{
    var fmt = "Label_Row{0:00}_Col{0:00}";
    for (var rowIndex = 0; rowIndex < 100; rowIndex++)
    {
        for (var colIndex = 0; colIndex < 100; colIndex++)
        {
            var lblName = String.Format(fmt, rowIndex, colIndex);
            foreach (var ctrl in this.Controls)
            {
                var lbl = ctrl as Label;
                if ((lbl != null) && (lbl.Name == lblName))
                {
                    lbl.Text = null;
                }
            }
        }
    }
}

How to set width of a div in percent in JavaScript?

Yes, it is:

<div id="myid">Some Content........</div>

document.getElementById('#myid').style.width = '50%';

Can someone explain how to implement the jQuery File Upload plugin?

Hi try bellow link it is very easy. I've been stuck for long time and it solve my issue in few minutes. http://simpleupload.michaelcbrook.com/#examples

Entity Framework select distinct name

Using lambda expression..

 var result = EFContext.TestAddresses.Select(m => m.Name).Distinct();

Another variation using where,

 var result = EFContext.TestAddresses
             .Where(a => a.age > 10)//if you have any condition
             .Select(m => m.name).Distinct();

Another variation using sql like syntax

 var result = (from recordset
              in EFContext.TestAddresses
              .where(a => a.city = 'vijaynagar')//if you have any condition
              .select new 
              {
                 recordset.name
              }).Distinct();

MySQL - Make an existing Field Unique

The easiest and fastest way would be with phpmyadmin structure table.

USE PHPMYADMIN ADMIN PANEL!

There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.

How to make function decorators and chain them together?

Paolo Bergantino's answer has the great advantage of only using the stdlib, and works for this simple example where there are no decorator arguments nor decorated function arguments.

However it has 3 major limitations if you want to tackle more general cases:

  • as already noted in several answers, you can not easily modify the code to add optional decorator arguments. For example creating a makestyle(style='bold') decorator is non-trivial.
  • besides, wrappers created with @functools.wraps do not preserve the signature, so if bad arguments are provided they will start executing, and might raise a different kind of error than the usual TypeError.
  • finally, it is quite difficult in wrappers created with @functools.wraps to access an argument based on its name. Indeed the argument can appear in *args, in **kwargs, or may not appear at all (if it is optional).

I wrote decopatch to solve the first issue, and wrote makefun.wraps to solve the other two. Note that makefun leverages the same trick than the famous decorator lib.

This is how you would create a decorator with arguments, returning truly signature-preserving wrappers:

from decopatch import function_decorator, DECORATED
from makefun import wraps

@function_decorator
def makestyle(st='b', fn=DECORATED):
    open_tag = "<%s>" % st
    close_tag = "</%s>" % st

    @wraps(fn)
    def wrapped(*args, **kwargs):
        return open_tag + fn(*args, **kwargs) + close_tag

    return wrapped

decopatch provides you with two other development styles that hide or show the various python concepts, depending on your preferences. The most compact style is the following:

from decopatch import function_decorator, WRAPPED, F_ARGS, F_KWARGS

@function_decorator
def makestyle(st='b', fn=WRAPPED, f_args=F_ARGS, f_kwargs=F_KWARGS):
    open_tag = "<%s>" % st
    close_tag = "</%s>" % st
    return open_tag + fn(*f_args, **f_kwargs) + close_tag

In both cases you can check that the decorator works as expected:

@makestyle
@makestyle('i')
def hello(who):
    return "hello %s" % who

assert hello('world') == '<b><i>hello world</i></b>'    

Please refer to the documentation for details.

How do you display JavaScript datetime in 12 hour AM/PM format?

A short and sweet implementation:

// returns date object in 12hr (AM/PM) format
var formatAMPM = function formatAMPM(d) {
    var h = d.getHours();
    return (h % 12 || 12)
        + ':' + d.getMinutes().toString().padStart(2, '0')
        + ' ' + (h < 12 ? 'A' : 'P') + 'M';
};

Logger slf4j advantages of formatting with {} instead of string concatenation

Since, String is immutable in Java, so the left and right String have to be copied into the new String for every pair of concatenation. So, better go for the placeholder.

How to bring back "Browser mode" in IE11?

Easiest way, especially if in MSDN,,wasted hours of my time, stupid MS

http://support.microsoft.com/kb/2900662/en-us?sd=rss

  1. Open the Developer Tools pane. To do this, press F12.
  2. Open the Emulation screen. To do this, press Ctrl+8.
  3. On the Document mode list under Mode, click 9.
  4. On the User agent string list under Mode, click Internet Explorer 9.

How to add a 'or' condition in #ifdef

I am really OCD about maintaining strict column limits, and not a fan of "\" line continuation because you can't put a comment after it, so here is my method.

//|ĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆĀÆ|//
#ifdef  CONDITION_01             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_02             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_03             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef              TEMP_MACRO   //|       |//
//|-  --  --  --  --  --  --  --  --  --  -|//

printf("[IF_CONDITION:(1|2|3)]\n");

//|-  --  --  --  --  --  --  --  --  --  -|//
#endif                           //|       |//
#undef              TEMP_MACRO   //|       |//
//|________________________________________|//

Is there a built-in function to print all the current properties and values of an object?

You can use the "dir()" function to do this.

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo
t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder
, 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'
 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault
ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he
version', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_
ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit
, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption
', 'winver']
>>>

Another useful feature is help.

>>> help(sys)
Help on built-in module sys:

NAME
    sys

FILE
    (built-in)

MODULE DOCS
    http://www.python.org/doc/current/lib/module-sys.html

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.

    Dynamic objects:

    argv -- command line arguments; argv[0] is the script pathname if known

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

Set ${COMMAND} to g++ on Linux

Under "Preprocessor Include Paths, Macros, etc." and "CDT GCC Built-in Compiler Settings" there is an undefined ${COMMAND} variable if you imported the sources from an existing Makefile project.

Eclipse tries to run that command to parse its stdout to find headers, but ${COMMAND} is not set by default, and so it is not able to do so.

I have explained this in more detail at: How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

It seems like you can also use the patch command. Put the diff in the root of the repository and run patch from the command line.

patch -i yourcoworkers.diff

or

patch -p0 -i yourcoworkers.diff

You may need to remove the leading folder structure if they created the diff without using --no-prefix.

If so, then you can remove the parts of the folder that don't apply using:

patch -p1 -i yourcoworkers.diff

The -p(n) signifies how many parts of the folder structure to remove.

More information on creating and applying patches here.

You can also use

git apply yourcoworkers.diff --stat 

to see if the diff by default will apply any changes. It may say 0 files affected if the patch is not applied correctly (different folder structure).

How to retrieve an element from a set without removing it?

To provide some timing figures behind the different approaches, consider the following code. The get() is my custom addition to Python's setobject.c, being just a pop() without removing the element.

from timeit import *

stats = ["for i in xrange(1000): iter(s).next()   ",
         "for i in xrange(1000): \n\tfor x in s: \n\t\tbreak",
         "for i in xrange(1000): s.add(s.pop())   ",
         "for i in xrange(1000): s.get()          "]

for stat in stats:
    t = Timer(stat, setup="s=set(range(100))")
    try:
        print "Time for %s:\t %f"%(stat, t.timeit(number=1000))
    except:
        t.print_exc()

The output is:

$ ./test_get.py
Time for for i in xrange(1000): iter(s).next()   :       0.433080
Time for for i in xrange(1000):
        for x in s:
                break:   0.148695
Time for for i in xrange(1000): s.add(s.pop())   :       0.317418
Time for for i in xrange(1000): s.get()          :       0.146673

This means that the for/break solution is the fastest (sometimes faster than the custom get() solution).

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

You may get day, month and year and may concatenate them or may use MM-dd-yyyy format as given below.

Date date1 = new Date();
String mmddyyyy1 = new SimpleDateFormat("MM-dd-yyyy").format(date1);
System.out.println("Formatted Date 1: " + mmddyyyy1);



Date date2 = new Date();
Calendar calendar1 = new GregorianCalendar();
calendar1.setTime(date2);
int day1   = calendar1.get(Calendar.DAY_OF_MONTH);
int month1 = calendar1.get(Calendar.MONTH) + 1; // {0 - 11}
int year1  = calendar1.get(Calendar.YEAR);
String mmddyyyy2 = ((month1<10)?"0"+month1:month1) + "-" + ((day1<10)?"0"+day1:day1) + "-" + (year1);
System.out.println("Formatted Date 2: " + mmddyyyy2);



LocalDateTime ldt1 = LocalDateTime.now();  
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM-dd-yyyy");  
String mmddyyyy3 = ldt1.format(format1);  
System.out.println("Formatted Date 3: " + mmddyyyy3);  



LocalDateTime ldt2 = LocalDateTime.now();
int day2 = ldt2.getDayOfMonth();
int mont2= ldt2.getMonthValue();
int year2= ldt2.getYear();
String mmddyyyy4 = ((mont2<10)?"0"+mont2:mont2) + "-" + ((day2<10)?"0"+day2:day2) + "-" + (year2);
System.out.println("Formatted Date 4: " + mmddyyyy4);



LocalDateTime ldt3 = LocalDateTime.of(2020, 6, 11, 14, 30); // int year, int month, int dayOfMonth, int hour, int minute
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("MM-dd-yyyy");  
String mmddyyyy5 = ldt3.format(format2);   
System.out.println("Formatted Date 5: " + mmddyyyy5); 



Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(new Date());
int day3  = calendar2.get(Calendar.DAY_OF_MONTH); // OR Calendar.DATE
int month3= calendar2.get(Calendar.MONTH) + 1;
int year3 = calendar2.get(Calendar.YEAR);
String mmddyyyy6 = ((month3<10)?"0"+month3:month3) + "-" + ((day3<10)?"0"+day3:day3) + "-" + (year3);
System.out.println("Formatted Date 6: " + mmddyyyy6);



Date date3 = new Date();
LocalDate ld1 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date3)); // Accepts only yyyy-MM-dd
int day4  = ld1.getDayOfMonth();
int month4= ld1.getMonthValue();
int year4 = ld1.getYear();
String mmddyyyy7 = ((month4<10)?"0"+month4:month4) + "-" + ((day4<10)?"0"+day4:day4) + "-" + (year4);
System.out.println("Formatted Date 7: " + mmddyyyy7);



Date date4 = new Date();
int day5   = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getDayOfMonth();
int month5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getMonthValue();
int year5  = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getYear();
String mmddyyyy8 = ((month5<10)?"0"+month5:month5) + "-" + ((day5<10)?"0"+day5:day5) + "-" + (year5);
System.out.println("Formatted Date 8: " + mmddyyyy8);



Date date5 = new Date();
int day6   = Integer.parseInt(new SimpleDateFormat("dd").format(date5));
int month6 = Integer.parseInt(new SimpleDateFormat("MM").format(date5));
int year6  = Integer.parseInt(new SimpleDateFormat("yyyy").format(date5));
String mmddyyyy9 = ((month6<10)?"0"+month6:month6) + "-" + ((day6<10)?"0"+day6:day6) + "-" + (year6);`enter code here`
System.out.println("Formatted Date 9: " + mmddyyyy9);

Understanding the Gemfile.lock file

I've spent the last few months messing around with Gemfiles and Gemfile.locks a lot whilst building an automated dependency update tool1. The below is far from definitive, but it's a good starting point for understanding the Gemfile.lock format. You might also want to check out the source code for Bundler's lockfile parser.

You'll find the following headings in a lockfile generated by Bundler 1.x:

GEM (optional but very common)

These are dependencies sourced from a Rubygems server. That may be the main Rubygems index, at Rubygems.org, or it may be a custom index, such as those available from Gemfury and others. Within this section you'll see:

  • remote: one or more lines specifying the location of the Rubygems index(es)
  • specs: a list of dependencies, with their version number, and the constraints on any subdependencies

GIT (optional)

These are dependencies sourced from a given git remote. You'll see a different one of these sections for each git remote, and within each section you'll see:

  • remote: the git remote. E.g., [email protected]:rails/rails
  • revision: the commit reference the Gemfile.lock is locked to
  • tag: (optional) the tag specified in the Gemfile
  • specs: the git dependency found at this remote, with its version number, and the constraints on any subdependencies

PATH (optional)

These are dependencies sourced from a given path, provided in the Gemfile. You'll see a different one of these sections for each path dependency, and within each section you'll see:

  • remote: the path. E.g., plugins/vendored-dependency
  • specs: the git dependency found at this remote, with its version number, and the constraints on any subdependencies

PLATFORMS

The Ruby platform the Gemfile.lock was generated against. If any dependencies in the Gemfile specify a platform then they will only be included in the Gemfile.lock when the lockfile is generated on that platform (e.g., through an install).

DEPENDENCIES

A list of the dependencies which are specified in the Gemfile, along with the version constraint specified there.

Dependencies specified with a source other than the main Rubygems index (e.g., git dependencies, path-based, dependencies) have a ! which means they are "pinned" to that source2 (although one must sometimes look in the Gemfile to determine in).

RUBY VERSION (optional)

The Ruby version specified in the Gemfile, when this Gemfile.lock was created. If a Ruby version is specified in a .ruby_version file instead this section will not be present (as Bundler will consider the Gemfile / Gemfile.lock agnostic to the installer's Ruby version).

BUNDLED WITH (Bundler >= v1.10.x)

The version of Bundler used to create the Gemfile.lock. Used to remind installers to update their version of Bundler, if it is older than the version that created the file.

PLUGIN SOURCE (optional and very rare)

In theory, a Gemfile can specify Bundler plugins, as well as gems3, which would then be listed here. In practice, I'm not aware of any available plugins, as of July 2017. This part of Bundler is still under active development!


  1. https://dependabot.com
  2. https://github.com/bundler/bundler/issues/4631
  3. http://andre.arko.net/2012/07/23/towards-a-bundler-plugin-system/

How to reverse MD5 to get the original string?

No, that's not really possible, as

  • there can be more than one string giving the same MD5
  • it was designed to be hard to "reverse"

The goal of the MD5 and its family of hashing functions is

  • to get short "extracts" from long string
  • to make it hard to guess where they come from
  • to make it hard to find collisions, that is other words having the same hash (which is a very similar exigence as the second one)

Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.

This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...

Where does mysql store data?

In version 5.6 at least, the Management tab in MySQL Workbench shows that it's in a hidden folder called ProgramData in the C:\ drive. My default data directory is

C:\ProgramData\MySQL\MySQL Server 5.6\data

. Each database has a folder and each table has a file here.

How to replace all occurrences of a string in Javascript?

If what you want to find is already in a string, and you don't have a regex escaper handy, you can use join/split:

_x000D_
_x000D_
    function replaceMulti(haystack, needle, replacement)_x000D_
    {_x000D_
        return haystack.split(needle).join(replacement);_x000D_
    }_x000D_
_x000D_
    someString = 'the cat looks like a cat';_x000D_
    console.log(replaceMulti(someString, 'cat', 'dog'));
_x000D_
_x000D_
_x000D_

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

Automatically running a batch file as an administrator

Runas.exe won't work here. You can use VBScript to invoke the "Run as Administrator" shell verb. The Elevation Powertoys contain a batchfile that allows you to invoke an elevated command:

elevatecmd.exe

http://blogs.technet.com/b/elevationpowertoys/

Placeholder in IE9

to make it work in IE-9 use below .it works for me

JQuery need to include:

jQuery(function() {
   jQuery.support.placeholder = false;
   webkit_type = document.createElement('input');
   if('placeholder' in webkit_type) jQuery.support.placeholder = true;});
   $(function() {

     if(!$.support.placeholder) {

       var active = document.activeElement;

       $(':text, textarea, :password').focus(function () {

       if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) &&         ($(this).attr('placeholder') != '') && $(this).val() == $(this).attr('placeholder')) {
          $(this).val('').removeClass('hasPlaceholder');
        }
      }).blur(function () {
if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) &&  ($(this).attr('placeholder') != '') && ($(this).val() == '' || $(this).val() ==   $(this).attr('placeholder'))) {
     $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});

$(':text, textarea, :password').blur();
$(active).focus();
$('form').submit(function () {
     $(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});

CSS Style need to include:

.hasPlaceholder {color: #aaa;}

Fetch API with Cookie

This works for me:

import Cookies from 'universal-cookie';
const cookies = new Cookies();

function headers(set_cookie=false) {
  let headers = {
    'Accept':       'application/json',
    'Content-Type': 'application/json',
    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
    headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}

Then build your call:

export function fetchTests(user_id) {
  return function (dispatch) {
   let data = {
    method:      'POST',
    credentials: 'same-origin',
    mode:        'same-origin',
    body:        JSON.stringify({
                     user_id: user_id
                }),
    headers:     headers(true)
   };
   return fetch('/api/v1/tests/listing/', data)
      .then(response => response.json())
      .then(json => dispatch(receiveTests(json)));
    };
  }

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

Happened to me when my client Smartgit put a newline in my .git/HEAD file. Deleting the empty line fixed it.

Change the Value of h1 Element within a Form with JavaScript

You can do it with regular JavaScript this way:

document.getElementById('h1_id').innerHTML = 'h1 content here';

Here is the doc for getElementById and the innerHTML property.

The innerHTML property description:

A DOMString containing the HTML serialization of the element's descendants. Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString.

Search for string and get count in vi editor

You need the n flag. To count words use:

:%s/\i\+/&/gn   

and a particular word:

:%s/the/&/gn        

See count-items documentation section.

If you simply type in:

%s/pattern/pattern/g

then the status line will give you the number of matches in vi as well.

Should I use typescript? or I can just use ES6?

Decision tree between ES5, ES6 and TypeScript

Do you mind having a build step?

  • Yes - Use ES5
  • No - keep going

Do you want to use types?

  • Yes - Use TypeScript
  • No - Use ES6

More Details

ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers

ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.

TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.

Execute jar file with multiple classpath libraries from command prompt

You can use maven-assembly-plugin, Here is the example from the official site: https://maven.apache.org/plugins/maven-assembly-plugin/usage.html

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.5.1</version>
        <configuration>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
            <archive>
                <manifest>
                    <mainClass>your main class</mainClass>
                </manifest>
            </archive>
        </configuration>
        <executions>
            <execution>
                <id>make-assembly</id> <!-- this is used for inheritance merges -->
                <phase>package</phase> <!-- bind to the packaging phase -->
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

Tensorflow 2.x Compatible Answer: Converting mrry's code to Tensorflow 2.x (>= 2.0) for the benefit of the community.

!pip install tensorflow==2.1
import tensorflow as tf

tf.compat.v1.disable_eager_execution()    

t = tf.constant(42.0)
sess = tf.compat.v1.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.compat.v1.get_default_session()
    assert t.eval() == sess.run(t)

#The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.multiply(t, u)
ut = tf.multiply(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

How do you handle multiple submit buttons in ASP.NET MVC Framework?

I would suggest interested parties have a look at Maarten Balliauw's solution. I think it is very elegant.

In case the link dissapears, it's using the MultiButton attribute applied to a controller action to indicate which button click that action should relate to.

Truncate all tables in a MySQL database in one command?

Use phpMyAdmin in this way:

Database View => Check All (tables) => Empty

If you want to ignore foreign key checks, you can uncheck the box that says:

[ ] Enable foreign key checks

You'll need to be running atleast version 4.5.0 or higher to get this checkbox.

Its not MySQL CLI-fu, but hey, it works!

A full list of all the new/popular databases and their uses?

To file under both 'established' and 'key-value store': Berkeley DB.

Has transactions and replication. Usually linked as a lib (no standalone server, although you may write one). Values and keys are just binary strings, you can provide a custom sorting function for them (where applicable).

Does not prevent from shooting yourself in the foot. Switch off locking/transaction support, access the db from two threads at once, end up with a corrupt file.

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

I am trying to connect my db docker container on Ubuntu 18.04, same problem.

First check your device by run nmcli dev to check if device docker0 is connected.

If it is not connected, try to restart docker service:

sudo service docker restart

How to get a list of column names

You can use pragma related commands in sqlite like below

pragma table_info("table_name")
--Alternatively
select * from pragma_table_info("table_name")

If you require column names like id|foo|bar|age|street|address, basically your answer is in below query.

select group_concat(name,'|') from pragma_table_info("table_name")

How to pass an array within a query string?

Check the parse_string function http://php.net/manual/en/function.parse-str.php

It will return all the variables from a query string, including arrays.

Example from php.net:

<?php
$strĀ =Ā "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echoĀ $first;Ā Ā //Ā value
echoĀ $arr[0];Ā //Ā fooĀ bar
echoĀ $arr[1];Ā //Ā baz

parse_str($str,Ā $output);
echoĀ $output['first'];Ā Ā //Ā value
echoĀ $output['arr'][0];Ā //Ā fooĀ bar
echoĀ $output['arr'][1];Ā //Ā baz

?>

Adding new line of data to TextBox

I find this method saves a lot of typing, and prevents a lot of typos.

string nl = "\r\n";

txtOutput.Text = "First line" + nl + "Second line" + nl + "Third line";

Error Importing SSL certificate : Not an X.509 Certificate

Does your cacerts.pem file hold a single certificate? Since it is a PEM, have a look at it (with a text editor), it should start with

-----BEGIN CERTIFICATE-----

and end with

-----END CERTIFICATE-----

Finally, to check it is not corrupted, get hold of openssl and print its details using

openssl x509 -in cacerts.pem -text

How to get the current time in Google spreadsheet using script editor?

The Date object is used to work with dates and times.

Date objects are created with new Date().

var date= new Date();

 function myFunction() {
        var currentTime = new Date();
        Logger.log(currentTime);
    }

Java - Get a list of all Classes loaded in the JVM

You might be able to get a list of classes that are loaded through the classloader but this would not include classes you haven't loaded yet but are on your classpath.

To get ALL classes on your classpath you have to do something like your second solution. If you really want classes that are currently "Loaded" (in other words, classes you have already referenced, accessed or instantiated) then you should refine your question to indicate this.

Dynamically add child components in React

Firstly a warning: you should never tinker with DOM that is managed by React, which you are doing by calling ReactDOM.render(<SampleComponent ... />);

With React, you should use SampleComponent directly in the main App.

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(<App/>, document.body);

The content of your Component is irrelevant, but it should be used like this:

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <SampleComponent name="SomeName"/>
            </div>
        );
    }
});

You can then extend your app component to use a list.

var App = React.createClass({
    render: function() {
        var componentList = [
            <SampleComponent name="SomeName1"/>,
            <SampleComponent name="SomeName2"/>
        ]; // Change this to get the list from props or state
        return (
            <div>
                <h1>App main component! </h1>
                {componentList}
            </div>
        );
    }
});

I would really recommend that you look at the React documentation then follow the "Get Started" instructions. The time you spend on that will pay off later.

https://facebook.github.io/react/index.html

How to parse JSON in Kotlin?

http://www.jsonschema2pojo.org/ Hi you can use this website to convert json to pojo.
control+Alt+shift+k

After that you can manualy convert that model class to kotlin model class. with the help of above shortcut.

Mapping many-to-many association table with extra column(s)

As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.

For instance, the implementation code of the extra class should look like that:

@Entity
@Table(name = "USER_SERVICES")
public class UserService{

    // example of auto-generated ID
    @Id
    @Column(name = "USER_SERVICES_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long userServiceID;



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SERVICE_ID")
    private Service service;



    // example of extra column
    @Column(name="VISIBILITY")    
    private boolean visibility;



    public long getUserServiceID() {
        return userServiceID;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(boolean visibility) {
        this.visibility = visibility;
    }

}

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

Get line number while using grep

If you want only the line number do this:

grep -n Pattern file.ext | gawk '{print $1}' FS=":"

Example:

$ grep -n 9780545460262 EXT20130410.txt | gawk '{print $1}' FS=":" 
48793
52285
54023

Problems installing the devtools package

Centos 6.8

this work like charm for me

  1. install libcurl $yum -y install libcurl libcurl-devel
  2. restart R Software $rstudio-server verify-installation

How to get the current branch name in Git?

git branch

should show all the local branches of your repo. The starred branch is your current branch.

If you want to retrieve only the name of the branch you are on, you can do:

git rev-parse --abbrev-ref HEAD

or with Git 2.22 and above:

git branch --show-current

How do I get length of list of lists in Java?

Just use

int listCount = data.size();

That tells you how many lists there are (assuming none are null). If you want to find out how many strings there are, you'll need to iterate:

int total = 0;
for (List<String> sublist : data) {
    // TODO: Null checking
    total += sublist.size();
}
// total is now the total number of strings

Can I return the 'id' field after a LINQ insert?

When inserting the generated ID is saved into the instance of the object being saved (see below):

protected void btnInsertProductCategory_Click(object sender, EventArgs e)
{
  ProductCategory productCategory = new ProductCategory();
  productCategory.Name = ā€œSample Categoryā€;
  productCategory.ModifiedDate = DateTime.Now;
  productCategory.rowguid = Guid.NewGuid();
  int id = InsertProductCategory(productCategory);
  lblResult.Text = id.ToString();
}

//Insert a new product category and return the generated ID (identity value)
private int InsertProductCategory(ProductCategory productCategory)
{
  ctx.ProductCategories.InsertOnSubmit(productCategory);
  ctx.SubmitChanges();
  return productCategory.ProductCategoryID;
}

reference: http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4

Modify SVG fill color when being served as Background-Image

Use the sepia filter along with hue-rotate, brightness, and saturation to create any color we want.

.colorize-pink {
  filter: brightness(0.5) sepia(1) hue-rotate(-70deg) saturate(5);
}

https://css-tricks.com/solved-with-css-colorizing-svg-backgrounds/

Add a new element to an array without specifying the index in Bash

As Dumb Guy points out, it's important to note whether the array starts at zero and is sequential. Since you can make assignments to and unset non-contiguous indices ${#array[@]} is not always the next item at the end of the array.

$ array=(a b c d e f g h)
$ array[42]="i"
$ unset array[2]
$ unset array[3]
$ declare -p array     # dump the array so we can see what it contains
declare -a array='([0]="a" [1]="b" [4]="e" [5]="f" [6]="g" [7]="h" [42]="i")'
$ echo ${#array[@]}
7
$ echo ${array[${#array[@]}]}
h

Here's how to get the last index:

$ end=(${!array[@]})   # put all the indices in an array
$ end=${end[@]: -1}    # get the last one
$ echo $end
42

That illustrates how to get the last element of an array. You'll often see this:

$ echo ${array[${#array[@]} - 1]}
g

As you can see, because we're dealing with a sparse array, this isn't the last element. This works on both sparse and contiguous arrays, though:

$ echo ${array[@]: -1}
i

Set default option in mat-select

Try this

<mat-form-field>
    <mat-select [(ngModel)]="modeselect" [placeholder]="modeselect">
        <mat-option value="domain">Domain</mat-option>
        <mat-option value="exact">Exact</mat-option>
    </mat-select>
</mat-form-field>

Component:

export class SelectValueBindingExample {
    public modeselect = 'Domain';
}

Live demo

Also, don't forget to import FormsModule in your app.module

How to dispatch a Redux action with a timeout?

I understand that this question is a bit old but I'm going to introduce another solution using redux-observable aka. Epic.

Quoting the official documentation:

What is redux-observable?

RxJS 5-based middleware for Redux. Compose and cancel async actions to create side effects and more.

An Epic is the core primitive of redux-observable.

It is a function which takes a stream of actions and returns a stream of actions. Actions in, actions out.

In more or less words, you can create a function that receives actions through a Stream and then return a new stream of actions (using common side effects such as timeouts, delays, intervals, and requests).

Let me post the code and then explain a bit more about it

store.js

import {createStore, applyMiddleware} from 'redux'
import {createEpicMiddleware} from 'redux-observable'
import {Observable} from 'rxjs'
const NEW_NOTIFICATION = 'NEW_NOTIFICATION'
const QUIT_NOTIFICATION = 'QUIT_NOTIFICATION'
const NOTIFICATION_TIMEOUT = 2000

const initialState = ''
const rootReducer = (state = initialState, action) => {
  const {type, message} = action
  console.log(type)
  switch(type) {
    case NEW_NOTIFICATION:
      return message
    break
    case QUIT_NOTIFICATION:
      return initialState
    break
  }

  return state
}

const rootEpic = (action$) => {
  const incoming = action$.ofType(NEW_NOTIFICATION)
  const outgoing = incoming.switchMap((action) => {
    return Observable.of(quitNotification())
      .delay(NOTIFICATION_TIMEOUT)
      //.takeUntil(action$.ofType(NEW_NOTIFICATION))
  });

  return outgoing;
}

export function newNotification(message) {
  return ({type: NEW_NOTIFICATION, message})
}
export function quitNotification(message) {
  return ({type: QUIT_NOTIFICATION, message});
}

export const configureStore = () => createStore(
  rootReducer,
  applyMiddleware(createEpicMiddleware(rootEpic))
)

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {configureStore} from './store.js'
import {Provider} from 'react-redux'

const store = configureStore()

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

App.js

import React, { Component } from 'react';
import {connect} from 'react-redux'
import {newNotification} from './store.js'

class App extends Component {

  render() {
    return (
      <div className="App">
        {this.props.notificationExistance ? (<p>{this.props.notificationMessage}</p>) : ''}
        <button onClick={this.props.onNotificationRequest}>Click!</button>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    notificationExistance : state.length > 0,
    notificationMessage : state
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onNotificationRequest: () => dispatch(newNotification(new Date().toDateString()))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App)

The key code to solve this problem is as easy as pie as you can see, the only thing that appears different from the other answers is the function rootEpic.

Point 1. As with sagas, you have to combine the epics in order to get a top level function that receives a stream of actions and returns a stream of actions, so you can use it with the middleware factory createEpicMiddleware. In our case we only need one so we only have our rootEpic so we don't have to combine anything but it's a good to know fact.

Point 2. Our rootEpic which takes care about the side effects logic only takes about 5 lines of code which is awesome! Including the fact that is pretty much declarative!

Point 3. Line by line rootEpic explanation (in comments)

const rootEpic = (action$) => {
  // sets the incoming constant as a stream 
  // of actions with  type NEW_NOTIFICATION
  const incoming = action$.ofType(NEW_NOTIFICATION)
  // Merges the "incoming" stream with the stream resulting for each call
  // This functionality is similar to flatMap (or Promise.all in some way)
  // It creates a new stream with the values of incoming and 
  // the resulting values of the stream generated by the function passed
  // but it stops the merge when incoming gets a new value SO!,
  // in result: no quitNotification action is set in the resulting stream
  // in case there is a new alert
  const outgoing = incoming.switchMap((action) => {
    // creates of observable with the value passed 
    // (a stream with only one node)
    return Observable.of(quitNotification())
      // it waits before sending the nodes 
      // from the Observable.of(...) statement
      .delay(NOTIFICATION_TIMEOUT)
  });
  // we return the resulting stream
  return outgoing;
}

I hope it helps!

Dynamically updating plot in matplotlib

Is there a way in which I can update the plot just by adding more point[s] to it...

There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the matplotlib cookbook examples? Also, check out the more modern animation examples in the matplotlib documentation. Finally, the animation API defines a function FuncAnimation which animates a function in time. This function could just be the function you use to acquire your data.

Each method basically sets the data property of the object being drawn, so doesn't require clearing the screen or figure. The data property can simply be extended, so you can keep the previous points and just keep adding to your line (or image or whatever you are drawing).

Given that you say that your data arrival time is uncertain your best bet is probably just to do something like:

import matplotlib.pyplot as plt
import numpy

hl, = plt.plot([], [])

def update_line(hl, new_data):
    hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
    hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
    plt.draw()

Then when you receive data from the serial port just call update_line.

Installing a pip package from within a Jupyter Notebook not working

In jupyter notebook under python 3.6, the following line works:

!source activate py36;pip install <...>

In Oracle, is it possible to INSERT or UPDATE a record through a view?

There are two times when you can update a record through a view:

  1. If the view has no joins or procedure calls and selects data from a single underlying table.
  2. If the view has an INSTEAD OF INSERT trigger associated with the view.

Generally, you should not rely on being able to perform an insert to a view unless you have specifically written an INSTEAD OF trigger for it. Be aware, there are also INSTEAD OF UPDATE triggers that can be written as well to help perform updates.

Android Gradle Apache HttpClient does not exist?

I ran into the same issue. Daniel Nugent's answer helped a bit (after following his advice HttpResponse was found - but the HttpClient was still missing).

So here is what fixed it for me:

  1. (if not already done, commend previous import-statements out)
  2. visit http://hc.apache.org/downloads.cgi
  3. get the 4.5.1.zip from the binary section
  4. unzip it and paste httpcore-4.4.3 & httpclient-4.5.1.jar in project/libs folder
  5. right-click the jar and choose Add as library.

Hope it helps.

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

Datetime in where clause

Assuming we're talking SQL Server DateTime

Note: BETWEEN includes both ends of the range, so technically this pattern will be wrong:

errorDate BETWEEN '12/20/2008' AND '12/21/2008'

My preferred method for a time range like that is:

'20081220' <= errorDate AND errordate < '20081221'

Works with common indexes (range scan, SARGable, functionless) and correctly clips off midnight of the next day, without relying on SQL Server's time granularity (e.g. 23:59:59.997)

Call a function after previous function is complete

you can do it like this

$.when(funtion1()).then(function(){
    funtion2();
})

How to convert a string to character array in c (or) how to extract a single char form string?

In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.

Therefore, to extract a character c at index i from string your_string, just use

char c = your_string[i];

Index is base 0 (first character is your_string[0], second is your_string[1]...).

count number of rows in a data frame in R based on group

The count() function in plyr does what you want:

library(plyr)

count(mydf, "MONTH-YEAR")

Promise.all().then() resolve?

Today NodeJS supports new async/await syntax. This is an easy syntax and makes the life much easier

async function process(promises) { // must be an async function
    let x = await Promise.all(promises);  // now x will be an array
    x = x.map( tmp => tmp * 10);              // proccessing the data.
}

const promises = [
   new Promise(resolve => setTimeout(resolve, 0, 1)),
   new Promise(resolve => setTimeout(resolve, 0, 2))
];

process(promises)

Learn more:

Put spacing between divs in a horizontal row?

This is because width when provided a % doesn't account for padding/margins. You will need to reduce the amount to possibly 24% or 24.5%. Once this is done you should be good, but you will need to provide different options based on the screen size if you want this to always work correct since you have a hardcoded margin, but a relative size.

PHP Remove elements from associative array

The way to do this to take your nested target array and copy it in single step to a non-nested array. Delete the key(s) and then assign the final trimmed array to the nested node of the earlier array. Here is a code to make it simple:

$temp_array = $list['resultset'][0];

unset($temp_array['badkey1']);
unset($temp_array['badkey2']);

$list['resultset'][0] = $temp_array;

How to declare a global variable in React?

Maybe it's using a sledge-hammer to crack a nut, but using environment variables (with Dotenv https://www.npmjs.com/package/dotenv) you can also provide values throughout your React app. And that without any overhead code where they are used.

I came here because I found that some of the variables defined in my env files where static throughout the different envs, so I searched for a way to move them out of the env files. But honestly I don't like any of the alternatives I found here. I don't want to set up and use a context everytime I need those values.

I am not experienced when it comes to environments, so please, if there is a downside to this approach, let me know.

How to execute logic on Optional if not present?

First of all, your dao.find() should either return an Optional<Obj> or you will have to create one.

e.g.

Optional<Obj> = dao.find();

or you can do it yourself like:

Optional<Obj> = Optional.ofNullable(dao.find());

this one will return Optional<Obj> if present or Optional.empty() if not present.

So now let's get to the solution,

public Obj getObjectFromDB() {
   return Optional.ofNullable(dao.find()).flatMap(ob -> {
            ob.setAvailable(true);
            return Optional.of(ob);    
        }).orElseGet(() -> {
            logger.fatal("Object not available");
            return null;
        });
    }

This is the one liner you're looking for :)

Dealing with commas in a CSV file

An example might help to show how commas can be displayed in a .csv file. Create a simple text file as follows:

Save this text file as a text file with suffix ".csv" and open it with Excel 2000 from Windows 10.

aa,bb,cc,d;d "In the spreadsheet presentation, the below line should look like the above line except the below shows a displayed comma instead of a semicolon between the d's." aa,bb,cc,"d,d", This works even in Excel

aa,bb,cc,"d,d", This works even in Excel 2000 aa,bb,cc,"d ,d", This works even in Excel 2000 aa,bb,cc,"d , d", This works even in Excel 2000

aa,bb,cc, " d,d", This fails in Excel 2000 due to the space belore the 1st quote aa,bb,cc, " d ,d", This fails in Excel 2000 due to the space belore the 1st quote aa,bb,cc, " d , d", This fails in Excel 2000 due to the space belore the 1st quote

aa,bb,cc,"d,d " , This works even in Excel 2000 even with spaces before and after the 2nd quote. aa,bb,cc,"d ,d " , This works even in Excel 2000 even with spaces before and after the 2nd quote. aa,bb,cc,"d , d " , This works even in Excel 2000 even with spaces before and after the 2nd quote.

Rule: If you want to display a comma in a a cell (field) of a .csv file: "Start and end the field with a double quotes, but avoid white space before the 1st quote"

Upload files with FTP using PowerShell

Easiest way

The most trivial way to upload a binary file to an FTP server using PowerShell is using WebClient.UploadFile:

$client = New-Object System.Net.WebClient
$client.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$client.UploadFile("ftp://ftp.example.com/remote/path/file.zip", "C:\local\path\file.zip")

Advanced options

If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, etc), use FtpWebRequest. Easy way is to just copy a FileStream to FTP stream using Stream.CopyTo:

$request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
$request.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile 

$fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
$ftpStream = $request.GetRequestStream()

$fileStream.CopyTo($ftpStream)

$ftpStream.Dispose()
$fileStream.Dispose()

Progress monitoring

If you need to monitor an upload progress, you have to copy the contents by chunks yourself:

$request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
$request.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile 

$fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
$ftpStream = $request.GetRequestStream()

$buffer = New-Object Byte[] 10240
while (($read = $fileStream.Read($buffer, 0, $buffer.Length)) -gt 0)
{
    $ftpStream.Write($buffer, 0, $read)
    $pct = ($fileStream.Position / $fileStream.Length)
    Write-Progress `
        -Activity "Uploading" -Status ("{0:P0} complete:" -f $pct) `
        -PercentComplete ($pct * 100)
}

$ftpStream.Dispose()
$fileStream.Dispose()

Uploading folder

If you want to upload all files from a folder, see
PowerShell Script to upload an entire folder to FTP

How to resize images proportionally / keeping the aspect ratio?

This totally worked for me for a draggable item - aspectRatio:true

.appendTo(divwrapper).resizable({
    aspectRatio: true,
    handles: 'se',
    stop: resizestop 
})

Content Type text/xml; charset=utf-8 was not supported by service

For anyone who lands here by searching:

content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8

or some subset of that error:

A similar error was caused in my case by building and running a service without proper attributes. I got this error message when I tried to update the service reference in my client application. It was resolved when I correctly applied [DataContract] and [DataMember] attributes to my custom classes.

This would most likely be applicable if your service was set up and working and then it broke after you edited it.

Does C have a string type?

First, you don't need to do all that. In particular, the strcpy is redundant - you don't need to copy a string just to printf it. Your message can be defined with that string in place.

Second, you've not allowed enough space for that "Hello, World!" string (message needs to be at least 14 characters, allowing the extra one for the null terminator).

On the why, though, it's history. In assembler, there are no strings, only bytes, words etc. Pascal had strings, but there were problems with static typing because of that - string[20] was a different type that string[40]. There were languages even in the early days that avoided this issue, but that caused indirection and dynamic allocation overheads which were much more of an efficiency problem back then.

C simply chose to avoid the overheads and stay very low level. Strings are character arrays. Arrays are very closely related to pointers that point to their first item. When array types "decay" to pointer types, the buffer-size information is lost from the static type, so you don't get the old Pascal string issues.

In C++, there's the std::string class which avoids a lot of these issues - and has the dynamic allocation overheads, but these days we usually don't care about that. And in any case, std::string is a library class - there's C-style character-array handling underneath.

TypeError: a bytes-like object is required, not 'str'

This code is probably good for Python 2. But in Python 3, this will cause an issue, something related to bit encoding. I was trying to make a simple TCP server and encountered the same problem. Encoding worked for me. Try this with sendto command.

clientSocket.sendto(message.encode(),(serverName, serverPort))

Similarly you would use .decode() to receive the data on the UDP server side, if you want to print it exactly as it was sent.

How can I define fieldset border color?

It works for me when I define the complete border property. (JSFiddle here)

.field_set{
 border: 1px #F00 solid;
}?

the reason is the border-style that is set to none by default for fieldsets. You need to override that as well.

How to change the type of a field?

I use this script in mongodb console for string to float conversions...

db.documents.find({ 'fwtweaeeba' : {$exists : true}}).forEach( function(obj) { 
        obj.fwtweaeeba = parseFloat( obj.fwtweaeeba ); 
        db.documents.save(obj); } );    

db.documents.find({ 'versions.0.content.fwtweaeeba' : {$exists : true}}).forEach( function(obj) { 
        obj.versions[0].content.fwtweaeeba = parseFloat( obj.versions[0].content.fwtweaeeba ); 
        db.documents.save(obj); } );

db.documents.find({ 'versions.1.content.fwtweaeeba' : {$exists : true}}).forEach( function(obj) { 
        obj.versions[1].content.fwtweaeeba = parseFloat( obj.versions[1].content.fwtweaeeba );  
        db.documents.save(obj); } );

db.documents.find({ 'versions.2.content.fwtweaeeba' : {$exists : true}}).forEach( function(obj) { 
        obj.versions[2].content.fwtweaeeba = parseFloat( obj.versions[2].content.fwtweaeeba );  
        db.documents.save(obj); } );

And this one in php)))

foreach($db->documents->find(array("type" => "chair")) as $document){
    $db->documents->update(
        array('_id' => $document[_id]),
        array(
            '$set' => array(
                'versions.0.content.axdducvoxb' => (float)$document['versions'][0]['content']['axdducvoxb'],
                'versions.1.content.axdducvoxb' => (float)$document['versions'][1]['content']['axdducvoxb'],
                'versions.2.content.axdducvoxb' => (float)$document['versions'][2]['content']['axdducvoxb'],
                'axdducvoxb' => (float)$document['axdducvoxb']
            )
        ),
        array('$multi' => true)
    );


}

Clear History and Reload Page on Login/Logout Using Ionic Framework

I was trying to do refresh page using angularjs when i saw websites i got confused but no code was working for the code then i got solution for reloading page using

$state.go('path',null,{reload:true});

use this in a function this will work.

List comprehension vs map

I ran a quick test comparing three methods for invoking the method of an object. The time difference, in this case, is negligible and is a matter of the function in question (see @Alex Martelli's response). Here, I looked at the following methods:

# map_lambda
list(map(lambda x: x.add(), vals))

# map_operator
from operator import methodcaller
list(map(methodcaller("add"), vals))

# map_comprehension
[x.add() for x in vals]

I looked at lists (stored in the variable vals) of both integers (Python int) and floating point numbers (Python float) for increasing list sizes. The following dummy class DummyNum is considered:

class DummyNum(object):
    """Dummy class"""
    __slots__ = 'n',

    def __init__(self, n):
        self.n = n

    def add(self):
        self.n += 5

Specifically, the add method. The __slots__ attribute is a simple optimization in Python to define the total memory needed by the class (attributes), reducing memory size. Here are the resulting plots.

Performance of mapping Python object methods

As stated previously, the technique used makes a minimal difference and you should code in a way that is most readable to you, or in the particular circumstance. In this case, the list comprehension (map_comprehension technique) is fastest for both types of additions in an object, especially with shorter lists.

Visit this pastebin for the source used to generate the plot and data.

How to Handle Button Click Events in jQuery?

Try This:

_x000D_
_x000D_
$(document).on('click', '#btnClick', function(){ _x000D_
    alert("button is clicked");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
 <button id="btnClick">Click me</button> 
_x000D_
_x000D_
_x000D_

IIS Express gives Access Denied error when debugging ASP.NET MVC

In my case (ASP.NET MVC 4 application), the Global.asax file was missing. It was appearing in Solution explorer with an exclamation mark. I replaced it and the error went away.

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

The Hibernate Validator requires ā€” but does not include ā€” an Expression Language (EL) implementation. Adding a dependency on one will will fix the issue.

<dependency>
   <groupId>org.glassfish</groupId>
   <artifactId>jakarta.el</artifactId>
   <version>3.0.3</version>
</dependency>

This requirement is documented in the Getting started with Hibernate Validator documentation. In a Java EE environment, it would be provided by the container. In a standalone application such as yours, it needs to be provided.

Hibernate Validator also requires an implementation of the Unified Expression Language (JSR 341) for evaluating dynamic expressions in constraint violation messages.

When your application runs in a Java EE container such as WildFly, an EL implementation is already provided by the container.

In a Java SE environment, however, you have to add an implementation as dependency to your POM file. For instance, you can add the following dependency to use the JSR 341 reference implementation:

<dependency>
  <groupId>org.glassfish</groupId>
  <artifactId>jakarta.el</artifactId>
  <version>${version.jakarta.el-api}</version>
</dependency>

There are other EL implementations that can be used other than Glassfish. For instance, Spring Boot versions 2.2.x and earlier by default used embedded Tomcat (it's since switched to use the Jakarta EL reference implementation). That version of EL can be used as follows:

<dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-el</artifactId>
   <version>9.0.41</version>
</dependency>

That said, in a Spring Boot project, typically one would use the spring-boot-starter-validation dependency rather than specifying the Hibernate validator & EL libraries directly. That dependency includes both hibernate-validator and the EL implementation.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
    <version>2.4.2.RELEASE</version>
</dependency>

How to call Stored Procedures with EntityFramework?

Basically you just have to map the procedure to the entity using Stored Procedure Mapping.

Once mapped, you use the regular method for adding an item in EF, and it will use your stored procedure instead.

Please see: This Link for a walkthrough. The result will be adding an entity like so (which will actually use your stored procedure)

using (var ctx = new SchoolDBEntities())
        {
            Student stud = new Student();
            stud.StudentName = "New sp student";
            stud.StandardId = 262;

            ctx.Students.Add(stud);
            ctx.SaveChanges();
        }

Submit form with Enter key without submit button?

$("input").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $("form").submit();
    }
});

What does the "yield" keyword do?

In Python generators (a special type of iterators) are used to generate series of values and yield keyword is just like the return keyword of generator functions.

The other fascinating thing yield keyword does is saving the state of a generator function.

So, we can set a number to a different value each time the generator yields.

Here's an instance:

def getPrimes(number):
    while True:
        if isPrime(number):
            number = yield number     # a miracle occurs here
        number += 1

def printSuccessivePrimes(iterations, base=10):
    primeGenerator = getPrimes(base)
    primeGenerator.send(None)
    for power in range(iterations):
        print(primeGenerator.send(base ** power))

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

How to format current time using a yyyyMMddHHmmss format?

This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:

t := time.Now()

t.Year()

t.Month()

t.Day()

t.Hour()

t.Minute()

t.Second()

For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:

t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
        t.Year(), t.Month(), t.Day(),
        t.Hour(), t.Minute(), t.Second())

As always, remember that docs are the best source of learning: https://golang.org/pkg/time/

How to delete large data of table in SQL without log?

@Francisco Goldenstein, just a minor correction. The COMMIT must be used after you set the variable, otherwise the WHILE will be executed just once:

DECLARE @Deleted_Rows INT;
SET @Deleted_Rows = 1;

WHILE (@Deleted_Rows > 0)
BEGIN
    BEGIN TRANSACTION

    -- Delete some small number of rows at a time
    DELETE TOP (10000)  LargeTable 
    WHERE readTime < dateadd(MONTH,-7,GETDATE())

    SET @Deleted_Rows = @@ROWCOUNT;

    COMMIT TRANSACTION
    CHECKPOINT -- for simple recovery model

END

"Could not find a valid gem in any repository" (rubygame and others)

For what it is worth I came to this page because I had the same problem. I never got anywhere except some IMAP stuff that I don't understand. Then I remembered I had uninstalled privoxy on my ubuntu (because of some weird runtime error that mentioned 127.0.0.1:8118 when I used Daniel Kehoe's Rails template, https://github.com/RailsApps/rails3-application-templates [never discovered what it was]) and I hadn't changed my terminal to the state of no system wide proxy, under network proxy.

I know this may not be on-point but if I wound up here maybe other privoxy users can benefit too.

What does the ">" (greater-than sign) CSS selector mean?

The greater sign ( > ) selector in CSS means that the selector on the right is a direct descendant / child of whatever is on the left.

An example:

article > p { }

Means only style a paragraph that comes after an article.

python getoutput() equivalent in subprocess

Use subprocess.Popen:

import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)

Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.

ascending/descending in LINQ - can one change the order via parameter?

What about ordering desc by the desired property,

   blah = blah.OrderByDescending(x => x.Property);

And then doing something like

  if (!descending)
  {
       blah = blah.Reverse()
  }
  else
  {
      // Already sorted desc ;)
  }

Is it Reverse() too slow?

Why is Java's SimpleDateFormat not thread-safe?

Here is a code example that proves the fault in the class. I've checked: the problem occurs when using parse and also when you are only using format.

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

Simply consider setting its value in the constructor of your entity class

public class Foo
{
       public DateTime DateCreated { get; set; }
       public Foo()
       {
           DateCreated = DateTime.Now;
       }

}

Draw in Canvas by finger, Android

You can use this class simply:

public class DoodleCanvas  extends View{

    private Paint mPaint;
    private Path mPath;

    public DoodleCanvas(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(10);
        mPath = new Path();
    }


    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(mPath, mPaint);
        super.onDraw(canvas);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()){

            case MotionEvent.ACTION_DOWN:
                mPath.moveTo(event.getX(), event.getY());
                break;

            case MotionEvent.ACTION_MOVE:
                mPath.lineTo(event.getX(), event.getY());
                invalidate();
                break;

            case MotionEvent.ACTION_UP:
                break;
        }

        return true;
    }
}

Converting a date string to a DateTime object using Joda Time library

You need a DateTimeFormatter appropriate to the format you're using. Take a look at the docs for instructions on how to build one.

Off the cuff, I think you need format = DateTimeFormat.forPattern("M/d/y H:m:s")

How to change a field name in JSON using Jackson

Be aware that there is org.codehaus.jackson.annotate.JsonProperty in Jackson 1.x and com.fasterxml.jackson.annotation.JsonProperty in Jackson 2.x. Check which ObjectMapper you are using (from which version), and make sure you use the proper annotation.

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

Answer

You need to create a header with a proper formatted User agent String, it server to communicate client-server.

You can check your own user agent Here.

Example

Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0

Third party Package user_agent 0.1.9

I found this module very simple to use, in one line of code it randomly generates a User agent string.

from user_agent import generate_user_agent, generate_navigator
from pprint import pprint

print(generate_user_agent())
# 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.3; Win64; x64)'

print(generate_user_agent(os=('mac', 'linux')))
# 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:36.0) Gecko/20100101 Firefox/36.0'

pprint(generate_navigator())

# {'app_code_name': 'Mozilla',
#  'app_name': 'Netscape',
#  'appversion': '5.0',
#  'name': 'firefox',
#  'os': 'linux',
#  'oscpu': 'Linux i686 on x86_64',
#  'platform': 'Linux i686 on x86_64',
#  'user_agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686 on x86_64; rv:41.0) Gecko/20100101 Firefox/41.0',
#  'version': '41.0'}

pprint(generate_navigator_js())

# {'appCodeName': 'Mozilla',
#  'appName': 'Netscape',
#  'appVersion': '38.0',
#  'platform': 'MacIntel',
#  'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:38.0) Gecko/20100101 Firefox/38.0'}

Java JTable setting Column Width

Use this code. It worked for me. I considered for 3 columns. Change the loop value for your code.

TableColumn column = null;
for (int i = 0; i < 3; i++) {
    column = table.getColumnModel().getColumn(i);
    if (i == 0) 
        column.setMaxWidth(10);
    if (i == 2)
        column.setMaxWidth(50);
}

Missing Push Notification Entitlement

This was what fixed it for me. (I had already tried toggling the capabilities on/off, recreating the provisioning profile, etc).

In the Build Settings tab, in Code Signing Entitlements, my .entitlements file wasn't link for all sections. Once I added it to the Any SDK section, the error was resolved.

enter image description here

Disable scrolling on `<input type=number>`

Typescript Variation

Typescript needs to know that you're working with an HTMLElement for type safety, else you'll see lots of Property 'type' does not exist on type 'Element' type of errors.

document.addEventListener("mousewheel", function(event){
  let numberInput = (<HTMLInputElement>document.activeElement);
  if (numberInput.type === "number") {
    numberInput.blur();
  }
});

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

What exactly is node.js used for?

Directly from the tag wiki, make sure watch some of the talk videos linked there to get a better idea.


Node.js is an event based, asynchronous I/O framework that uses Google's V8 JavaScript Engine.

Node.js - or just Node as it's commonly called - is used for developing applications that make heavy use of the ability to run JavaScript both on the client, as well as on server side and therefore benefit from the re-usability of code and the lack of context switching.

It's also possible to use matured JavaScript frameworks like YUI and jQuery for server side DOM manipulation.

To ease the development of complex JavaScript further, Node.js supports the CommonJS standard that allows for modularized development and the distribution of software in packages via the Node Package Manager.

Applications that can be written using Node.js include, but are not limited to:

  • Static file servers
  • Web Application frameworks
  • Messaging middle ware
  • Servers for HTML5 multi player games

Copy data from another Workbook through VBA

Are you looking for the syntax to open them:

Dim wkbk As Workbook

Set wkbk = Workbooks.Open("C:\MyDirectory\mysheet.xlsx")

Then, you can use wkbk.Sheets(1).Range("3:3") (or whatever you need)

How can I discover the "path" of an embedded resource?

The name of the resource is the name space plus the "pseudo" name space of the path to the file. The "pseudo" name space is made by the sub folder structure using \ (backslashes) instead of . (dots).

public static Stream GetResourceFileStream(String nameSpace, String filePath)
{
    String pseduoName = filePath.Replace('\\', '.');
    Assembly assembly = Assembly.GetExecutingAssembly();
    return assembly.GetManifestResourceStream(nameSpace + "." + pseduoName);
}

The following call:

GetResourceFileStream("my.namespace", "resources\\xml\\my.xml")

will return the stream of my.xml located in the folder-structure resources\xml in the name space: my.namespace.

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

Microsoft itself posted a KB article about this, and that article has a service pack that they claim fixes the problem. See below.

http://support.microsoft.com/kb/959417/

It took a while for the associated update to install itself, but once it did, I was able to run the Visual Studio setup successfully from the Add/Remove Programs control panel.

Set value to an entire column of a pandas dataframe

df.loc[:,'industry'] = 'yyy'

This does the magic. You are to add '.loc' with ':' for all rows. Hope it helps

How to get current foreground activity context in android?

Update 3: There is an official api added for this, please use ActivityLifecycleCallbacks instead.

tr:hover not working

Recently I had a similar problem, the problem was I was using background-color, use background: {anyColor}

example:

tr::hover td {background: red;}

This works like charm!

How to get URL parameter using jQuery or plain JavaScript?

A slight improvement to Sameer's answer, cache params into closure to avoid parsing and looping through all parameters each time calling

var getURLParam = (function() {
    var paramStr = decodeURIComponent(window.location.search).substring(1);
    var paramSegs = paramStr.split('&');
    var params = [];
    for(var i = 0; i < paramSegs.length; i++) {
        var paramSeg = paramSegs[i].split('=');
        params[paramSeg[0]] = paramSeg[1];
    }
    console.log(params);
    return function(key) {
        return params[key];
    }
})();

Retaining file permissions with Git

In pre-commit/post-checkout an option would be to use "mtree" (FreeBSD), or "fmtree" (Ubuntu) utility which "compares a file hierarchy against a specification, creates a specification for a file hierarchy, or modifies a specification."

The default set are flags, gid, link, mode, nlink, size, time, type, and uid. This can be fitted to the specific purpose with -k switch.

WAITING at sun.misc.Unsafe.park(Native Method)

From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.

onKeyDown event not working on divs in React

You need to write it this way

<div 
    className="player"
    style={{ position: "absolute" }}
    onKeyDown={this.onKeyPressed}
    tabIndex="0"
  >

If onKeyPressed is not bound to this, then try to rewrite it using arrow function or bind it in the component constructor.

load json into variable

  • this will get JSON file externally to your javascript variable.
  • now this sample_data will contain the values of JSON file.

var sample_data = '';
$.getJSON("sample.json", function (data) {
    sample_data = data;
    $.each(data, function (key, value) {
        console.log(sample_data);
    });
});

Declare variable in SQLite and use it

I found one solution for assign variables to COLUMN or TABLE:

conn = sqlite3.connect('database.db')
cursor=conn.cursor()
z="Cash_payers"   # bring results from Table 1 , Column: Customers and COLUMN 
# which are pays cash
sorgu_y= Customers #Column name
query1="SELECT  * FROM  Table_1 WHERE " +sorgu_y+ " LIKE ? "
print (query1)
query=(query1)
cursor.execute(query,(z,))

Don't forget input one space between the WHERE and double quotes and between the double quotes and LIKE

How can I convert String to Int?

You can convert string to int many different type methods in C#

First one is mostly use :

string test = "123";
int x = Convert.ToInt16(test);

if int value is higher you should use int32 type.

Second one:

int x = int.Parse(text);

if you want to error check, you can use TryParse method. In below I add nullable type;

int i=0;
Int32.TryParse(text, out i) ? i : (int?)null);

Enjoy your codes....

Pandas DataFrame column to list

You can use pandas.Series.tolist

e.g.:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

Run:

>>> df['a'].tolist()

You will get

>>> [1, 2, 3]

Incomplete type is not allowed: stringstream

#include <sstream> and use the fully qualified name i.e. std::stringstream ss;

Center content in responsive bootstrap navbar

Update 2020...

Bootstrap 5 Beta

The Navbar is still flexbox based in Bootstrap 5 and centering content works the same as it did with Bootstrap 4. Examples

Bootstrap 4

Centering Navbar content is easier is Bootstrap 4, and you can see many centering scenarios explained here: https://stackoverflow.com/a/20362024/171456

Bootstrap 3

Another scenario that doesn't seem to have been answered yet is centering both the brand and navbar links. Here's a solution..

.navbar .navbar-header,
.navbar-collapse {
    float:none;
    display:inline-block;
    vertical-align: top;
}

@media (max-width: 768px) {
    .navbar-collapse  {
        display: block;
    }
}

http://codeply.com/go/1lrdvNH9GI

Also see: Bootstrap NavBar with left, center or right aligned items

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

Batch script to delete files

Lets say you saved your software onto your desktop.
if you want to remove an entire folder like an uninstaller program you could use this.

cd C:\Users\User\Detsktop\
rd /s /q SOFTWARE

this will delete the entire folder called software and all of its files and subfolders

Make Sure You Delete The Correct Folder Cause This Does Not Have A Yes / No Option

How to start a Process as administrator mode in C#

var pass = new SecureString();
pass.AppendChar('s');
pass.AppendChar('e');
pass.AppendChar('c');
pass.AppendChar('r');
pass.AppendChar('e');
pass.AppendChar('t');
Process.Start("notepad", "admin", pass, "");

Works also with ProcessStartInfo:

var psi = new ProcessStartInfo
{
    FileName = "notepad",
    UserName = "admin",
    Domain = "",
    Password = pass,
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true
};
Process.Start(psi);

Delaying function in swift

 NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHere", userInfo: nil, repeats: false)

This would call the function functionHere() with a 3 seconds delay

Python error: AttributeError: 'module' object has no attribute

The way I would do it is to leave the __ init__.py files empty, and do:

import lib.mod1.mod11
lib.mod1.mod11.mod12()

or

from lib.mod1.mod11 import mod12
mod12()

You may find that the mod1 dir is unnecessary, just have mod12.py in lib.

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

Mongodb v3.4

You need to do the following to create a secure database:

Make sure the user starting the process has permissions and that the directories exist (/data/db in this case).

1) Start MongoDB without access control.

mongod --port 27017 --dbpath /data/db

2) Connect to the instance.

mongo --port 27017

3) Create the user administrator (in the admin authentication database).

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

4) Re-start the MongoDB instance with access control.

mongod --auth --port 27017 --dbpath /data/db

5) Connect and authenticate as the user administrator.

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

6) Create additional users as needed for your deployment (e.g. in the test authentication database).

use test
db.createUser(
  {
    user: "myTester",
    pwd: "xyz123",
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

7) Connect and authenticate as myTester.

mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"

I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/

How to unpublish an app in Google Play Developer Console

There are two ways to delete an application you have uploaded from the Google Play Developer Console based off of the application's status within the Console. An app's status can be viewed from the "All Applications" tab listed in the furthest column. (See below)

enter image description here

  • If your app has not yet been published to the Google Play store (ie. Is still a draft):

Select your app from the list and at the top of the page, underneath your application name, it will say DRAFT in blue with the super low-profile option to delete it just to the right. Observe below:

enter image description here

Click that and you're done! Keep in mind: all of the work you have put into this application so far will be deleted from the Google Play Developer Console.

  • If your app has already been published and you want to remove it from the app store:

This method is similar, however it should be noted that it is not possible to permanently delete an app from your Developer Console once it has been published to the Play Store.

1) Select the application you would like to publish from the "All Applications" tab on the right of the screen

2) Below the title of the app, similar to how it was with the DRAFT application, there will be super low-profile text allowing you the option to unpublish your app from the Play Store. This process "may take a few hours to complete" as it is said by the Developer Console.

(Pictures on the way. As you have seen, my example app is still pending publication, lol)

I hope this helps to answer some people's questions.

Redirect output of mongo query to a csv file

Extending other answers:

I found @GEverding's answer most flexible. It also works with aggregation:

test_db.js

print("name,email");

db.users.aggregate([
    { $match: {} }
]).forEach(function(user) {
        print(user.name+","+user.email);
    }
});

Execute the following command to export results:

mongo test_db < ./test_db.js >> ./test_db.csv

Unfortunately, it adds additional text to the CSV file which requires processing the file before we can use it:

MongoDB shell version: 3.2.10 
connecting to: test_db

But we can make mongo shell stop spitting out those comments and only print what we have asked for by passing the --quiet flag

mongo --quiet test_db < ./test_db.js >> ./test_db.csv

Installing packages in Sublime Text 2

Try using Sublime Package Control to install your packages.

Also take a look at these tips

Python: Checking if a 'Dictionary' is empty doesn't seem to work

Empty dictionaries evaluate to False in Python:

>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>

Thus, your isEmpty function is unnecessary. All you need to do is:

def onMessage(self, socket, message):
    if not self.users:
        socket.send("Nobody is online, please use REGISTER command" \
                    " in order to register into the server")
    else:
        socket.send("ONLINE " + ' ' .join(self.users.keys()))