Programs & Examples On #Custom membershipprovider

Angular 4 default radio button checked by default

You can use [(ngModel)], but you'll need to update your value to [value] otherwise the value is evaluating as a string. It would look like this:

<label>This rule is true if:</label>
<label class="form-check-inline">
    <input class="form-check-input" type="radio" name="mode" [value]="true" [(ngModel)]="rule.mode">
</label>
<label class="form-check-inline">
    <input class="form-check-input" type="radio" name="mode" [value]="false" [(ngModel)]="rule.mode">
</label>

If rule.mode is true, then that radio is selected. If it's false, then the other.

The difference really comes down to the value. value="true" really evaluates to the string 'true', whereas [value]="true" evaluates to the boolean true.

What are the -Xms and -Xmx parameters when starting JVM?

The question itself has already been addressed above. Just adding part of the default values.

As per http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html

The default value of Xmx will depend on platform and amount of memory available in the system.

Pass object to javascript function

function myFunction(arg) {
    alert(arg.var1 + ' ' + arg.var2 + ' ' + arg.var3);
}

myFunction ({ var1: "Option 1", var2: "Option 2", var3: "Option 3" });

How to determine if .NET Core is installed

It doesn't need a installation process.

I have pinned "VSCore" on my taskbar (win10), so open it, and open a task manager choose "Visual Studio Core" process expand left arrow and over any of them child process right button over it and click in "Open File Location" menu.

If you don't remember where is installed search "Code.exe" file in all your hard drives.

How to find the installed pandas version

In a jupyter notebook cell: pip freeze | grep pandas enter image description here

Removing first x characters from string?

Another way (depending on your actual needs): If you want to pop the first n characters and save both the popped characters and the modified string:

s = 'lipsum'
n = 3
a, s = s[:n], s[n:]
print(a)
# lip
print(s)
# sum

Creating multiline strings in JavaScript

If you're willing to use the escaped newlines, they can be used nicely. It looks like a document with a page border.

enter image description here

FIX CSS <!--[if lt IE 8]> in IE

I found cascading it works great for multibrowser detection.

This code was used to change a fade to show/hide in ie 8 7 6.

$(document).ready(function(){
    if(jQuery.browser.msie && jQuery.browser.version.substring(0, 1) == 8.0)
         { 
             $(".glow").hide();
            $('#shop').hover(function() {
        $(".glow").show();
    }, function() {
        $(".glow").hide();
    });
         }
         else
         { if(jQuery.browser.msie && jQuery.browser.version.substring(0, 1) == 7.0)
         { 
             $(".glow").hide();
            $('#shop').hover(function() {
        $(".glow").show();
    }, function() {
        $(".glow").hide();
    });
         }
         else
         {if(jQuery.browser.msie && jQuery.browser.version.substring(0, 1) == 6.0)
         { 
             $(".glow").hide();
            $('#shop').hover(function() {
        $(".glow").show();
    }, function() {
        $(".glow").hide();
    });
         }
         else
         { $('#shop').hover(function() {
        $(".glow").stop(true).fadeTo("400ms", 1);
    }, function() {
        $(".glow").stop(true).fadeTo("400ms", 0.2);});
         }
         }
         }
       });

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

Have you been trying to reference your custom MapFragment class in the layout file?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <fragment
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mapFragment"
        android:name="com.nfc.demo.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Trying to create a file in Android: open failed: EROFS (Read-only file system)

Here is simple sample from android developer.

Basically, you can write a file in the internal storage like this :

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

Real-world examples of recursion

Parsing a tree of controls in Windows Forms or WebForms (.NET Windows Forms / ASP.NET).

HTML5 best practices; section/header/aside/article elements

[explanations in my “main answer”]

line 7. section around the whole website? Or only a div?

Neither. For styling: use the <body>, it’s already there. For sectioning/semantics: as detailed in my example HTML its effect is contrary to usefulness. Extra wrappers to already wrapped content is no improvement, but noise.


line 8. Each section start with a header?

No, it is the author’s choice where to put content typically summarized as “header”. And if that header-content is clearly recognizable without extra marking, it may perfectly stay without <header>. This is also the author’s choice.


line 23. Is this div right? or must this be a section?

The <div> is probably wrong. It depends on the intentions: is it for styling only it could be right. If it’s for semantic purposes it is wrong: it should be an <article> instead as shown in my other answer. <article> is also right if it is for both styling and sectioning combined.

<section> looks wrong here, as there are no similar sections before or after this one, like chapters in a book. (This is the purpose of <section>).


line 24. Split left/right column with a div.

No. Why?


line 25. Right place for the article tag?

Yes, makes sense.


line 26. Is it required to put your h1-tag in the header-tag?

No. A lone <h*> element probably never needs to go in a <header> (but it can if you want to) as it is already clear that it’s the heading of what is about to come. – It would make sense if that <header> also encompassed a tagline (marked with <p>), for example.


line 43. The content is not related to the main article, so I decided this is a section and not an aside.

It is a misunderstanding that an <aside> has to be “tangentially related” to the content around. The point is: use an <aside> if the content is only “tangentially related” or not at all!

Nevertheless, apart from <aside> being a decent choice, <article> might still be better than a <section> as “hot items” and “new items” are not to be read like two chapters in a book. You can perfectly go for one of them and not the other like an alternative sorting of something, not like two parts of a whole.


line 44. H2 without header

Is great.


line 53. section without header

Well, there is no <header>, but the <h2>-heading leaves pretty clear which part in this section is the header.


line 63. Div with all (non-related) news items

<article> or <aside> might be better.


line 64. header with h2

Discussed already.


line 65. Hmm, div or section? Or remove this div and only use the article-tag

Exactly! Remove the <div>.


line 105. Footer :-)

Very reasonable.

How to regex in a MySQL query

I think you can use REGEXP instead of LIKE

SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')

How to convert HH:mm:ss.SSS to milliseconds?

You can use SimpleDateFormat to do it. You just have to know 2 things.

  1. All dates are internally represented in UTC
  2. .getTime() returns the number of milliseconds since 1970-01-01 00:00:00 UTC.
package se.wederbrand.milliseconds;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Main {        
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

        String inputString = "00:01:30.500";

        Date date = sdf.parse("1970-01-01 " + inputString);
        System.out.println("in milliseconds: " + date.getTime());        
    }
}

CSS selector for disabled input type="submit"

I used @jensgram solution to hide a div that contains a disabled input. So I hide the entire parent of the input.

Here is the code :

div:has(>input[disabled=disabled]) {
    display: none;
}

Maybe it could help some of you.

Comparing two input values in a form validation with AngularJS

I need to do this just in one form in my entire application and i see a directive like a super complicate for my case, so i use the ng-patter like some has point, but have some problems, when the string has special characters like .[\ this broke, so i create a function for scape special characters.

$scope.escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

and in the view

<form name="ExampleForm">
  <label>Password</label>
  <input ng-model="password" required />
  <br>
   <label>Confirm password</label>
  <input ng-model="confirmPassword" required ng-pattern="escapeRegExp(password)"/>  
</form>

Check time difference in Javascript

The time diff in milliseconds

firstDate.getTime() - secondDate.getTime() 

HTML 5 video or audio playlist

You can add an event listener with 'ended' as the first param

Like this :

https://stackoverflow.com/a/2880950/6839331

What does ON [PRIMARY] mean?

When you create a database in Microsoft SQL Server you can have multiple file groups, where storage is created in multiple places, directories or disks. Each file group can be named. The PRIMARY file group is the default one, which is always created, and so the SQL you've given creates your table ON the PRIMARY file group.

See MSDN for the full syntax.

Convert audio files to mp3 using ffmpeg

1) wav to mp3

ffmpeg -i audio.wav -acodec libmp3lame audio.mp3

2) ogg to mp3

ffmpeg -i audio.ogg -acodec libmp3lame audio.mp3

3) ac3 to mp3

ffmpeg -i audio.ac3 -acodec libmp3lame audio.mp3

4) aac to mp3

ffmpeg -i audio.aac -acodec libmp3lame audio.mp3

Including another class in SCSS

Another option could be using an Attribute Selector:

[class^="your-class-name"]{
  //your style here
}

Whereas every class starting with "your-class-name" uses this style.

So in your case, you could do it like so:

[class^="class"]{
  display: inline-block;
  //some other properties
  &:hover{
   color: darken(#FFFFFF, 10%);
 }  
}

.class-b{
  //specifically for class b
  width: 100px;
  &:hover{
     color: darken(#FFFFFF, 20%);
  }
}

More about Attribute Selectors on w3Schools

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

Table relationships vs. entity relationships

In a relational database system, there can be only three types of table relationships:

  • one-to-many (via a Foreign Key column)
  • one-to-one (via a shared Primary Key)
  • many-to-many (via a link table with two Foreign Keys referencing two separate parent tables)

So, a one-to-many table relationship looks as follows:

one-to-many table relationship

Note that the relationship is based on the Foreign Key column (e.g., post_id) in the child table.

So, there is a single source of truth when it comes to managing a one-to-many table relationship.

Now, if you take a bidirectional entity relationship that maps on the one-to-many table relationship we saw previously:

Bidirectional One-To-Many entity association

If you take a look at the diagram above, you can see that there are two ways to manage this relationship.

In the Post entity, you have the comments collection:

@OneToMany(
    mappedBy = "post",
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();

And, in the PostComment, the post association is mapped as follows:

@ManyToOne(
    fetch = FetchType.LAZY
)
@JoinColumn(name = "post_id")
private Post post;

So, you have two sides that can change the entity association:

  • By adding an entry in the comments child collection, a new post_comment row should be associated with the parent post entity via its post_id column.
  • By setting the post property of the PostComment entity, the post_id column should be updated as well.

Because there are two ways to represent the Foreign Key column, you must define which is the source of truth when it comes to translating the association state change into its equivalent Foreign Key column value modification.

MappedBy (a.k.a the inverse side)

The mappedBy attribute tells that the @ManyToOne side is in charge of managing the Foreign Key column, and the collection is used only to fetch the child entities and to cascade parent entity state changes to children (e.g., removing the parent should also remove the child entities).

It's called the inverse side because it references the child entity property that manages this table relationship.

Synchronize both sides of a bidirectional association

Now, even if you defined the mappedBy attribute and the child-side @ManyToOne association manages the Foreign Key column, you still need to synchronize both sides of the bidirectional association.

The best way to do that is to add these two utility methods:

public void addComment(PostComment comment) {
    comments.add(comment);
    comment.setPost(this);
}

public void removeComment(PostComment comment) {
    comments.remove(comment);
    comment.setPost(null);
}

The addComment and removeComment methods ensure that both sides are synchronized. So, if we add a child entity, the child entity needs to point to the parent and the parent entity should have the child contained in the child collection.

ComboBox.SelectedText doesn't give me the SelectedText

I face this problem 5 minutes before.

I think that a solution (with visual studio 2005) is:

myString = comboBoxTest.GetItemText(comboBoxTest.SelectedItem);

Forgive me if I am wrong.

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

I solved this problem by using the following,

@await Html.PartialAsync("_ValidationScriptsPartial")

Node update a specific package

Use npm outdated to see Current and Latest version of all packages.


Then npm i packageName@versionNumber to install specific version : example npm i [email protected].

Or npm i packageName@latest to install latest version : example npm i browser-sync@latest.

How to find the minimum value in an ArrayList, along with the index number? (Java)

Here's what I do. I find the minimum first then after the minimum is found, it is removed from ArrayList.

ArrayList<Integer> a = new ArrayList<>();
a.add(3);
a.add(6);
a.add(2);
a.add(5);

while (a.size() > 0) {
    int min = 1000;
    for (int b:a) {
        if (b < min)
            min = b;
    }
    System.out.println("minimum: " + min);
    System.out.println("index of min: " + a.indexOf((Integer) min));
    a.remove((Integer) min);
}

Using "&times" word in html changes to ×

You need to escape:

<div class="test">&amp;times</div>

And then read the value using text() to get the unescaped value:

alert($(".test").text()); // outputs: &times

RE error: illegal byte sequence on Mac OS X

You simply have to pipe an iconv command before the sed command. Ex with file.txt input :

iconv -f ISO-8859-1 -t UTF8-MAC file.txt | sed 's/something/àéèêçùû/g' | .....

-f option is the 'from' codeset and -t option is the 'to' codeset conversion.

Take care of case, web pages usually show lowercase like that < charset=iso-8859-1"/> and iconv uses uppercase. You have list of iconv supported codesets in you system with command iconv -l

UTF8-MAC is modern OS Mac codeset for conversion.

Creating a config file in PHP

Define will make the constant available everywhere in your class without needing to use global, while the variable requires global in the class, I would use DEFINE. but again, if the db params should change during program execution you might want to stick with variable.

How to read an entire file to a string using C#?

How about File.ReadAllText:

string contents = File.ReadAllText(@"C:\temp\test.txt");

How to set image on QPushButton?

You can also use:

button.setStyleSheet("qproperty-icon: url(:/path/to/images.png);");

Note: This is a little hacky. You should use this only as last resort. Icons should be set from C++ code or Qt Designer.

How do I create/edit a Manifest file?

The simplest way to create a manifest is:

Project Properties -> Security -> Click "enable ClickOnce security settings" 
(it will generate default manifest in your project Properties) -> then Click 
it again in order to uncheck that Checkbox -> open your app.maifest and edit 
it as you wish.

Manifest location preview

Android Material and appcompat Manifest merger failed

I faced same error when i try to add Kotlin-KTX library to my project.

I try to AndroidX migration, and problem fixed!

Refactor/Migrate to AndroidX

How to Rotate a UIImage 90 degrees?

Simple. Just change the image orientation flag.

UIImage *oldImage = [UIImage imageNamed:@"whatever.jpg"];
UIImageOrientation newOrientation;
switch (oldImage.imageOrientation) {
    case UIImageOrientationUp:
        newOrientation = UIImageOrientationLandscapeLeft;
        break;
    case UIImageOrientationLandscapeLeft:
        newOrientation = UIImageOrientationDown;
        break;
    case UIImageOrientationDown:
        newOrientation = UIImageOrientationLandscapeRight;
        break;
    case UIImageOrientationLandscapeRight:
        newOrientation = UIImageOrientationUp;
        break;
    // you can also handle mirrored orientations similarly ...
}
UIImage *rotatedImage = [UIImage imageWithCGImage:oldImage.CGImage scale:1.0f orientation:newOrientation];

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

I usually don't have any JAVA_HOME environment variable. Java can set it up itself. Inside java java.home system property should be available.

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

App installation failed due to application-identifier entitlement

I had this problem and was not able to resolve it without deleting and reinstalling the app (messing with provisioning profiles, as some here suggested, did not help).

However, I did not lose my existing test data. Here's how to do that, for anyone having this problem in the future:

  1. Before removing the app, open the Xcode "Devices" window (that's cmd-shift-2).
  2. Select your device and find your app in the "Installed Apps" list.
  3. Click on the gear icon and select "Download Container...". This will copy all of the app's data to your Mac. Save that somewhere for now.
  4. Delete the app and reinstall it from Xcode. Kill the app from Xcode (click the stop button), so it's not running.
  5. Back in the "Devices" window, click the gear icon and select "Replace Container...". Select the data that you downloaded to your Mac in step 3.

Xcode will then restore your previously saved app data. You now have your old test data back, and the app should run.

CSS last-child selector: select last-element of specific class, not last child inside of parent?

if the last element type is article too, last-of-type will not work as expected.

maybe i not really understand how it work.

demo

Android Imagebutton change Image OnClick

You have assing button to your imgButton variable:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imgButton = (Button) findViewById(R.id.imgButton);
    imgButton.setOnClickListener(imgButtonHandler);
}

How to install latest version of Node using Brew

After installation/upgrading node via brew I ran into this issue exactly: the node command worked but not the npm command.

I used these commands to fix it.

brew uninstall node
brew update
brew upgrade
brew cleanup
brew install node
sudo chown -R $(whoami) /usr/local
brew link --overwrite node
brew postinstall node

I pieced together this solution after trial and error using...

Java method: Finding object in array list given a known attribute value

If you have to get an attribute that is not the ID. I would use CollectionUtils.

Dog someDog = new Dog();
Dog dog = CollectionUtils(dogList, new Predicate() {

@Override
public boolean evaluate(Object o)
{
    Dog d = (Dog)o;
    return someDog.getName().equals(d.getName());
}
});

Get Value From Select Option in Angular 4

You just need to put [(ngModel)] on your select element:

<select class="form-control col-lg-8" #corporation required [(ngModel)]="selectedValue">

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint such as Gmail, and you'll be vulnerable to a Man-in-the-Middle Attack.

Be sure you fully understand the security issues before using this as a solution.

You can add below code in /config/mail.php ( tested and worked on laravel 5.1, 5.2, 5.4 )

'stream' => [
   'ssl' => [
      'allow_self_signed' => true,
      'verify_peer' => false,
      'verify_peer_name' => false,
   ],
],

Enable UTF-8 encoding for JavaScript

This is a quite old request to reply but I want to give a short answer for newcommers. I had the same problem while working on an eight-languaged site. The problem is IDE based. The solution is to use Komodo Edit as code-editor. I tried many editors until I found one which doesnt change charset-settings of my pages. Dreamweaver (or almost all of others) change all pages code-page/charset settings whenever you change it for page. When you have changes in more than one page and have changed charset of any file then clicked "Save all", all open pages (including unchanged but assumed changed by editor because of charset) are silently re-assigned the new charset and all mismatching pages are broken down. I lost months on re-translating messages again and again until I discovered that Komodo Edit keeps settings separately for each file.

Android - how to make a scrollable constraintlayout?

you need surrounded my constraint-layout with a ScrollView tag and gave it the property android:isScrollContainer="true".

Importing CommonCrypto in a Swift framework

It happened the same to me after updating Xcode. I tried everything I can do such as reinstalling cocoapods and cleaning the project, but it didn't work. Now it's been solved after restart the system.

HTTP POST Returns Error: 417 "Expectation Failed."

Does the form you are trying to emulate have two fields, username and password?

If so, this line:

 postData.Add("username", "password");

is not correct.

you would need two lines like:

 postData.Add("username", "Moose");
postData.Add("password", "NotMoosespasswordreally");

Edit:

Okay, since that is not the problem, one way to tackle this is to use something like Fiddler or Wireshark to watch what is being sent to the web server from the browser successfully, then compare that to what is being sent from your code. If you are going to a normal port 80 from .Net, Fiddler will still capture this traffic.

There is probably some other hidden field on the form that the web server is expecting that you are not sending.

Casting to string in JavaScript

They do behave differently when the value is null.

  • null.toString() throws an error - Cannot call method 'toString' of null
  • String(null) returns - "null"
  • null + "" also returns - "null"

Very similar behaviour happens if value is undefined (see jbabey's answer).

Other than that, there is a negligible performance difference, which, unless you're using them in huge loops, isn't worth worrying about.

maxReceivedMessageSize and maxBufferSize in app.config

If you are using a custom binding, you can set the values like this:

<customBinding>
    <binding name="x">
        <httpsTransport maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
    </binding>
</customBinding>

Git: How do I list only local branches?

just the plain command

git branch

Why doesn't height: 100% work to expand divs to the screen height?

In the page source I see the following:

<div class="holder"> 
    <div id="s7" style="position: relative; width: 1366px; height: 474px; overflow: hidden;">

If you put the height value in the tag, it will use this instead of the height defined in the css file.

SQL SERVER, SELECT statement with auto generate row id

Select (Select count(y.au_lname) from dbo.authors y
where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid,
x.au_lname,x.au_fname from authors x group by au_lname,au_fname
order by Counterid --Alternatively that can be done which is equivalent as above..

Animate text change in UILabel

Swift 4.2 solution (taking 4.0 answer and updating for new enums to compile)

extension UIView {
    func fadeTransition(_ duration:CFTimeInterval) {
        let animation = CATransition()
        animation.timingFunction = CAMediaTimingFunction(name:
            CAMediaTimingFunctionName.easeInEaseOut)
        animation.type = CATransitionType.fade
        animation.duration = duration
        layer.add(animation, forKey: CATransitionType.fade.rawValue)
    }
}

func updateLabel() {
myLabel.fadeTransition(0.4)
myLabel.text = "Hello World"
}

Reading data from DataGridView in C#

something like

for (int rows = 0; rows < dataGrid.Rows.Count; rows++)
{
     for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++)
    {
        string value = dataGrid.Rows[rows].Cells[col].Value.ToString();

    }
} 

example without using index

foreach (DataGridViewRow row in dataGrid.Rows)
{ 
    foreach (DataGridViewCell cell in row.Cells)
    {
        string value = cell.Value.ToString();

    }
}

Using Pairs or 2-tuples in Java

With lombok it's easy to declare a Pair class:

@Data(staticConstructor = "of")
public class Pair<A, B> {
    private final A left;
    private final B right;
}

This will generates getters, static constructor named "of", equals(), hashcode() and toString().

see @Data documentation for more information

Removing the remembered login and password list in SQL Server Management Studio

In my scenario I only wanted to remove a specific username/password from the list which had many other saved connections I didn't want to forget. It turns out the SqlStudio.bin file others are discussing here is a .NET binary serialization of the Microsoft.SqlServer.Management.UserSettings.SqlStudio class, which can be deserialized, modified and reserialized to modify specific settings.

To accomplish removal of the specific login, I created a new C# .Net 4.6.1 console application and added a reference to the namespace which is located in the following dll: C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\Microsoft.SqlServer.Management.UserSettings.dll (your path may differ slightly depending on SSMS version)

From there I could easily create and modify the settings as desired:

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.SqlServer.Management.UserSettings;

class Program
{
    static void Main(string[] args)
    {
        var settingsFile = new FileInfo(@"C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\13.0\SqlStudio.bin");

        // Backup our original file just in case...
        File.Copy(settingsFile.FullName, settingsFile.FullName + ".backup");

        BinaryFormatter fmt = new BinaryFormatter();

        SqlStudio settings = null;

        using(var fs = settingsFile.Open(FileMode.Open))
        {
            settings = (SqlStudio)fmt.Deserialize(fs);
        }

        // The structure of server types / servers / connections requires us to loop
        // through multiple nested collections to find the connection to be removed.
        // We start here with the server types

        var serverTypes = settings.SSMS.ConnectionOptions.ServerTypes;

        foreach (var serverType in serverTypes)
        {
            foreach (var server in serverType.Value.Servers)
            {
                // Will store the connection for the provided server which should be removed
                ServerConnectionSettings removeConn = null;

                foreach (var conn in server.Connections)
                {
                    if (conn.UserName == "adminUserThatShouldBeRemoved")
                    {
                        removeConn = conn;
                        break;
                    }
                }

                if (removeConn != null)
                {
                    server.Connections.RemoveItem(removeConn);
                }
            }
        }

        using (var fs = settingsFile.Open(FileMode.Create))
        {
            fmt.Serialize(fs, settings);
        }
    }
}

How to insert values in table with foreign key using MySQL?

Case 1: Insert Row and Query Foreign Key

Here is an alternate syntax I use:

INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = (
       SELECT id_teacher
         FROM tab_teacher
        WHERE name_teacher = 'Dr. Smith')

I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department and expenses tables from the following:

enter image description here

Case 2: Insert Row and Then Insert Dependant Row

Luckily, MySQL supports LAST_INSERT_ID() exactly for this purpose.

INSERT INTO tab_teacher
   SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = LAST_INSERT_ID()

fatal error LNK1169: one or more multiply defined symbols found in game programming

The two int variables are defined in the header file. This means that every source file which includes the header will contain their definition (header inclusion is purely textual). The of course leads to multiple definition errors.

You have several options to fix this.

  1. Make the variables static (static int WIDTH = 1024;). They will still exist in each source file, but their definitions will not be visible outside of the source file.

  2. Turn their definitions into declarations by using extern (extern int WIDTH;) and put the definition into one source file: int WIDTH = 1024;.

  3. Probably the best option: make the variables const (const int WIDTH = 1024;). This makes them static implicitly, and also allows them to be used as compile-time constants, allowing the compiler to use their value directly instead of issuing code to read it from the variable etc.

Cannot read property 'getContext' of null, using canvas

I guess the problem is your js runs before the html is loaded.

If you are using jquery, you can use the document ready function to wrap your code:

$(function() {
    var Grid = function(width, height) {
        // codes...
    }
});

Or simply put your js after the <canvas>.

How do I compute derivative using Numpy?

I'll throw another method on the pile...

scipy.interpolate's many interpolating splines are capable of providing derivatives. So, using a linear spline (k=1), the derivative of the spline (using the derivative() method) should be equivalent to a forward difference. I'm not entirely sure, but I believe using a cubic spline derivative would be similar to a centered difference derivative since it uses values from before and after to construct the cubic spline.

from scipy.interpolate import InterpolatedUnivariateSpline

# Get a function that evaluates the linear spline at any x
f = InterpolatedUnivariateSpline(x, y, k=1)

# Get a function that evaluates the derivative of the linear spline at any x
dfdx = f.derivative()

# Evaluate the derivative dydx at each x location...
dydx = dfdx(x)

SELECT INTO a table variable in T-SQL

First create a temp table :

Step 1:

create table #tblOm_Temp (

    Name varchar(100),
    Age Int ,
    RollNumber bigint
)

**Step 2: ** Insert Some value in Temp table .

insert into #tblom_temp values('Om Pandey',102,1347)

Step 3: Declare a table Variable to hold temp table data.

declare   @tblOm_Variable table(

    Name Varchar(100),
    Age int,
    RollNumber bigint
)

Step 4: select value from temp table and insert into table variable.

insert into @tblOm_Variable select * from #tblom_temp

Finally value is inserted from a temp table to Table variable

Step 5: Can Check inserted value in table variable.

select * from @tblOm_Variable

Calling dynamic function with dynamic number of parameters

You could use .apply()

You need to specify a this... I guess you could use the this within mainfunc.

function mainfunc (func)
{
    var args = new Array();
    for (var i = 1; i < arguments.length; i++)
        args.push(arguments[i]);

    window[func].apply(this, args);
}

What is a clearfix?

The clearfix allows a container to wrap its floated children. Without a clearfix or equivalent styling, a container does not wrap around its floated children and collapses, just as if its floated children were positioned absolutely.

There are several versions of the clearfix, with Nicolas Gallagher and Thierry Koblentz as key authors.

If you want support for older browsers, it's best to use this clearfix :

.clearfix:before, .clearfix:after {
    content: "";
    display: table;
}

.clearfix:after {
    clear: both;
}

.clearfix {
    *zoom: 1;
}

In SCSS, you could use the following technique :

%clearfix {
    &:before, &:after {
        content:" ";
        display:table;
    }

    &:after {
        clear:both;
    }

    & {
        *zoom:1;
    }
}

#clearfixedelement {
    @extend %clearfix;
}

If you don't care about supporting older browsers, there's a shorter version :

.clearfix:after {
    content:"";
    display:table;
    clear:both;
}

Can I dispatch an action in reducer?

redux-loop takes a cue from Elm and provides this pattern.

How to have an auto incrementing version number (Visual Studio)?

  • Star in version (like "2.10.3.*") - it is simple, but the numbers are too large

  • AutoBuildVersion - looks great but its dont work on my VS2010.

  • @DrewChapin's script works, but I can not in my studio set different modes for Debug pre-build event and Release pre-build event.

so I changed the script a bit... commamd:

"%CommonProgramFiles(x86)%\microsoft shared\TextTemplating\10.0\TextTransform.exe" -a !!$(ConfigurationName)!1 "$(ProjectDir)Properties\AssemblyInfo.tt"

and script (this works to the "Debug" and "Release" configurations):

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#
    int incRevision = 1;
    int incBuild = 1;

    try { incRevision = Convert.ToInt32(this.Host.ResolveParameterValue("","","Debug"));} catch( Exception ) { incBuild=0; }
    try { incBuild = Convert.ToInt32(this.Host.ResolveParameterValue("","","Release")); } catch( Exception ) { incRevision=0; }
    try {
        string currentDirectory = Path.GetDirectoryName(Host.TemplateFile);
        string assemblyInfo = File.ReadAllText(Path.Combine(currentDirectory,"AssemblyInfo.cs"));
        Regex pattern = new Regex("AssemblyVersion\\(\"\\d+\\.\\d+\\.(?<revision>\\d+)\\.(?<build>\\d+)\"\\)");
        MatchCollection matches = pattern.Matches(assemblyInfo);
        revision = Convert.ToInt32(matches[0].Groups["revision"].Value) + incRevision;
        build = Convert.ToInt32(matches[0].Groups["build"].Value) + incBuild;
    }
    catch( Exception ) { }
#>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Game engine. Keys: F2 (Debug trace), F4 (Fullscreen), Shift+Arrows (Move view). ")]
[assembly: AssemblyProduct("Game engine")]
[assembly: AssemblyDescription("My engine for game")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © Name 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. Only Windows
// assemblies support COM.
[assembly: ComVisible(false)]

// On Windows, the following GUID is for the ID of the typelib if this
// project is exposed to COM. On other platforms, it unique identifies the
// title storage container when deploying this assembly to the device.
[assembly: Guid("00000000-0000-0000-0000-000000000000")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("0.1.<#= this.revision #>.<#= this.build #>")]
[assembly: AssemblyFileVersion("0.1.<#= this.revision #>.<#= this.build #>")]

<#+
    int revision = 0;
    int build = 0;
#>

Find CRLF in Notepad++

Make this setting. Menu-> View-> Show Symbol-> uncheck Show End of the Line

How do I create a folder in VB if it doesn't exist?

You should try using the File System Object or FSO. There are many methods belonging to this object that check if folders exist as well as creating new folders.

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

Change one value based on another value in pandas

I found it much easier to debut by printing out where each row meets the condition:

for n in df.columns:
    if(np.where(df[n] == 103)):
        print(n)
        print(df[df[n] == 103].index)

Group by in LINQ

var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key,
                           /**/car = g.Select(g=>g.car).FirstOrDefault()/**/}

IndexError: tuple index out of range ----- Python

A tuple consists of a number of values separated by commas. like

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345

tuple are index based (and also immutable) in Python.

Here in this case x = rows[1][1] + " " + rows[1][2] have only two index 0, 1 available but you are trying to access the 3rd index.

NULL or BLANK fields (ORACLE)

A NULL column is not countable, however a row that has a NULL column is. So, this should do what you're looking for:

SELECT COUNT (*) FROM TABLE WHERE COL_NAME IS NULL OR LENGTH(TRIM (COL_NAME)) = 0

Note, that there are non-printing characters that this will not address. For example U+00A0 is the non-breaking space character and a line containing that will visually appear empty, but will not be found by the tests above.

Forbidden You don't have permission to access /wp-login.php on this server

Sometimes if you are using some simple login info like this: username: 'admin' and pass: 'admin', the hosting is seeing you as a potential Brute Force Attack through WP login file, and blocks you IP address or that particularly file.

I had that issue with ixwebhosting and just got that info from their support guy. They must unban your IP in this situation. And you must change your WP admin login info to something more secure.

That solved my problem.

Better way to find last used row

I use this routine to find the count of data rows. There is a minimum of overhead required, but by counting using a decreasing scale, even a very large result requires few iterations. For example, a result of 28,395 would only require 2 + 8 + 3 + 9 + 5, or 27 times through the loop, instead of a time-expensive 28,395 times.

Even were we to multiply that by 10 (283,950), the iteration count is the same 27 times.

Dim lWorksheetRecordCountScaler as Long
Dim lWorksheetRecordCount as Long

Const sDataColumn = "A"   '<----Set to column that has data in all rows (Code, ID, etc.)

    'Count the data records
    lWorksheetRecordCountScaler = 100000  'Begin by counting in 100,000-record bites
    lWorksheetRecordCount = lWorksheetRecordCountScaler

    While lWorksheetRecordCountScaler >= 1

        While Sheets("Sheet2").Range(sDataColumn & lWorksheetRecordCount + 2).Formula > " "
            lWorksheetRecordCount = lWorksheetRecordCount + lWorksheetRecordCountScaler
        Wend

        'To the beginning of the previous bite, count 1/10th of the scale from there
        lWorksheetRecordCount = lWorksheetRecordCount - lWorksheetRecordCountScaler
        lWorksheetRecordCountScaler = lWorksheetRecordCountScaler / 10

    Wend

    lWorksheetRecordCount = lWorksheetRecordCount + 1   'Final answer

Should you commit .gitignore into the Git repos?

You typically do commit .gitignore. In fact, I personally go as far as making sure my index is always clean when I'm not working on something. (git status should show nothing.)

There are cases where you want to ignore stuff that really isn't project specific. For example, your text editor may create automatic *~ backup files, or another example would be the .DS_Store files created by OS X.

I'd say, if others are complaining about those rules cluttering up your .gitignore, leave them out and instead put them in a global excludes file.

By default this file resides in $XDG_CONFIG_HOME/git/ignore (defaults to ~/.config/git/ignore), but this location can be changed by setting the core.excludesfile option. For example:

git config --global core.excludesfile ~/.gitignore

Simply create and edit the global excludesfile to your heart's content; it'll apply to every git repository you work on on that machine.

How to implement a confirmation (yes/no) DialogPreference?

Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.

Unfortunately, it is in the com.android.internal.preference package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).

Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).

You can then add it to your preferences.xml like any other Preference. Example:

<com.example.myapp.YesNoPreference
    android:dialogMessage="Are you sure you want to revert all settings to their default values?"
    android:key="com.example.myapp.pref_reset_settings_key"
    android:summary="Revert all settings to their default values."
    android:title="Reset Settings" />

Which looks like this:

screenshot

What does "TypeError 'xxx' object is not callable" means?

The other answers detail the reason for the error. A possible cause (to check) may be your class has a variable and method with the same name, which you then call. Python accesses the variable as a callable - with ().

e.g. Class A defines self.a and self.a():

>>> class A:
...     def __init__(self, val):
...         self.a = val
...     def a(self):
...         return self.a
...
>>> my_a = A(12)
>>> val = my_a.a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>

Unable to start the mysql server in ubuntu

I think this is because you are using client software and not the server.

  • mysql is client
  • mysqld is the server

Try: sudo service mysqld start

To check that service is running use: ps -ef | grep mysql | grep -v grep.

Uninstalling:

sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean

Re-Installing:

sudo apt-get update
sudo apt-get install mysql-server

Backup entire folder before doing this:

sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade

Resizing an Image without losing any quality

There is something out there, context aware resizing, don't know if you will be able to use it, but it's worth looking at, that's for sure

A nice video demo (Enlarging appears towards the middle) http://www.youtube.com/watch?v=vIFCV2spKtg

Here there could be some code. http://www.semanticmetadata.net/2007/08/30/content-aware-image-resizing-gpl-implementation/

Was that overkill? Maybe there are some easy filters you can apply to an enlarged image to blur the pixels a bit, you could look into that.

How can I find a specific file from a Linux terminal?

Find from root path find / -name "index.html"

Find from current path find . -name "index.html"

Viewing unpushed Git commits

You could try....

gitk

I know it is not a pure command line option but if you have it installed and are on a GUI system it's a great way to see exactly what you are looking for plus a whole lot more.

(I'm actually kind of surprised no one mentioned it so far.)

How to properly seed random number generator

If your aim is just to generate a sting of random number then I think it's unnecessary to complicate it with multiple function calls or resetting seed every time.

The most important step is to call seed function just once before actually running rand.Init(x). Seed uses the provided seed value to initialize the default Source to a deterministic state. So, It would be suggested to call it once before the actual function call to pseudo-random number generator.

Here is a sample code creating a string of random numbers

package main 
import (
    "fmt"
    "math/rand"
    "time"
)



func main(){
    rand.Seed(time.Now().UnixNano())

    var s string
    for i:=0;i<10;i++{
    s+=fmt.Sprintf("%d ",rand.Intn(7))
    }
    fmt.Printf(s)
}

The reason I used Sprintf is because it allows simple string formatting.

Also, In rand.Intn(7) Intn returns, as an int, a non-negative pseudo-random number in [0,7).

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

This is the best way to enable/ disable swipe to pop view controller in iOS 10, Swift 3 :

For First Screen [ Where you want to Disable Swipe gesture ] :

class SignUpViewController : UIViewController,UIGestureRecognizerDelegate {

//MARK: - View initializers
override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    swipeToPop()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func swipeToPop() {

    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true;
    self.navigationController?.interactivePopGestureRecognizer?.delegate = self;
}

func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {

    if gestureRecognizer == self.navigationController?.interactivePopGestureRecognizer {
        return false
    }
    return true
} }

For middle screen [ Where you want to Enable Swipe gesture ] :

class FriendListViewController : UIViewController {

//MARK: - View initializers
override func viewDidLoad() {

    super.viewDidLoad()
    swipeToPop()
}

func swipeToPop() {

    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true;
    self.navigationController?.interactivePopGestureRecognizer?.delegate = nil;
} }

<strong> vs. font-weight:bold & <em> vs. font-style:italic

HTML represents meaning; CSS represents appearance. How you mark up text in a document is not determined by how that text appears on screen, but simply what it means. As another example, some other HTML elements, like headings, are styled font-weight: bold by default, but they are marked up using <h1><h6>, not <strong> or <b>.

In HTML5, you use <strong> to indicate important parts of a sentence, for example:

<p><strong>Do not touch.</strong> Contains <strong>hazardous</strong> materials.

And you use <em> to indicate linguistic stress, for example:

<p>A Gentleman: I suppose he does. But there's no point in asking.
<p>A Lady: Why not?
<p>A Gentleman: Because he doesn't row.
<p>A Lady: He doesn't <em>row</em>?
<p>A Gentleman: No. He <em>doesn't</em> row.
<p>A Lady: Ah. I see what you mean.

These elements are semantic elements that just happen to have bold and italic representations by default, but you can style them however you like. For example, in the <em> sample above, you could represent stress emphasis in uppercase instead of italics, but the functional purpose of the <em> element remains the same — to change the context of a sentence by emphasizing specific words or phrases over others:

em {
    font-style: normal;
    text-transform: uppercase;
}

Note that the original answer (below) applied to HTML standards prior to HTML5, in which <strong> and <em> had somewhat different meanings, <b> and <i> were purely presentational and had no semantic meaning whatsoever. Like <strong> and <em> respectively, they have similar presentational defaults but may be styled differently.


You use <strong> and <em> to indicate intense emphasis and normal emphasis respectively.

Or think of it this way: font-weight: bold is closer to <b> than <strong>, and font-style: italic is closer to <i> than <em>. These visual styles are purely visual: tools like screen readers aren't going to understand what bold and italic mean, but some screen readers are able to read <strong> and <em> text in a more emphasized tone.

How can I give the Intellij compiler more heap space?

I was facing "java.lang.OutOfMemoryError: Java heap space" error while building my project using maven install command.

I was able to get rid of it by changing maven runner settings.

Settings | Build, Execution, Deployment | Build Tools | Maven | Runner | VM options to -Xmx512m

Python one-line "for" expression

for item in array: array2.append (item)

Or, in this case:

array2 += array

Equivalent of explode() to work with strings in MySQL

First of all you should change database structure - the score in this case is some kind of composite value and should be stored in two columns, eg. score_host, score_guest.


MySQL doesn't provide explode() equivalent however in this case you could use SUBSTRING() and LOCATE() to cut off score of a host and a guest.

SELECT 
   CONVERT(SUBSTRING(score, 1, LOCATE('-',score) - 2) USING INTEGER) as score_host,
   CONVERT(SUBSTRING(score, LOCATE('-',score)+2) USING INTEGER) as score_guest
FROM ...;

CONVERT() is used to cast a string "23" into number 23.

Assignment inside lambda expression in Python

The assignment expression operator := added in Python 3.8 supports assignment inside of lambda expressions. This operator can only appear within a parenthesized (...), bracketed [...], or braced {...} expression for syntactic reasons. For example, we will be able to write the following:

import sys
say_hello = lambda: (
    message := "Hello world",
    sys.stdout.write(message + "\n")
)[-1]
say_hello()

In Python 2, it was possible to perform local assignments as a side effect of list comprehensions.

import sys
say_hello = lambda: (
    [None for message in ["Hello world"]],
    sys.stdout.write(message + "\n")
)[-1]
say_hello()

However, it's not possible to use either of these in your example because your variable flag is in an outer scope, not the lambda's scope. This doesn't have to do with lambda, it's the general behaviour in Python 2. Python 3 lets you get around this with the nonlocal keyword inside of defs, but nonlocal can't be used inside lambdas.

There's a workaround (see below), but while we're on the topic...


In some cases you can use this to do everything inside of a lambda:

(lambda: [
    ['def'
        for sys in [__import__('sys')]
        for math in [__import__('math')]

        for sub in [lambda *vals: None]
        for fun in [lambda *vals: vals[-1]]

        for echo in [lambda *vals: sub(
            sys.stdout.write(u" ".join(map(unicode, vals)) + u"\n"))]

        for Cylinder in [type('Cylinder', (object,), dict(
            __init__ = lambda self, radius, height: sub(
                setattr(self, 'radius', radius),
                setattr(self, 'height', height)),

            volume = property(lambda self: fun(
                ['def' for top_area in [math.pi * self.radius ** 2]],

                self.height * top_area))))]

        for main in [lambda: sub(
            ['loop' for factor in [1, 2, 3] if sub(
                ['def'
                    for my_radius, my_height in [[10 * factor, 20 * factor]]
                    for my_cylinder in [Cylinder(my_radius, my_height)]],

                echo(u"A cylinder with a radius of %.1fcm and a height "
                     u"of %.1fcm has a volume of %.1fcm³."
                     % (my_radius, my_height, my_cylinder.volume)))])]],

    main()])()

A cylinder with a radius of 10.0cm and a height of 20.0cm has a volume of 6283.2cm³.
A cylinder with a radius of 20.0cm and a height of 40.0cm has a volume of 50265.5cm³.
A cylinder with a radius of 30.0cm and a height of 60.0cm has a volume of 169646.0cm³.

Please don't.


...back to your original example: though you can't perform assignments to the flag variable in the outer scope, you can use functions to modify the previously-assigned value.

For example, flag could be an object whose .value we set using setattr:

flag = Object(value=True)
input = [Object(name=''), Object(name='fake_name'), Object(name='')] 
output = filter(lambda o: [
    flag.value or bool(o.name),
    setattr(flag, 'value', flag.value and bool(o.name))
][0], input)
[Object(name=''), Object(name='fake_name')]

If we wanted to fit the above theme, we could use a list comprehension instead of setattr:

    [None for flag.value in [bool(o.name)]]

But really, in serious code you should always use a regular function definition instead of a lambda if you're going to be doing outer assignment.

flag = Object(value=True)
def not_empty_except_first(o):
    result = flag.value or bool(o.name)
    flag.value = flag.value and bool(o.name)
    return result
input = [Object(name=""), Object(name="fake_name"), Object(name="")] 
output = filter(not_empty_except_first, input)

Python subprocess/Popen with a modified environment

With Python 3.5 you could do it this way:

import os
import subprocess

my_env = {**os.environ, 'PATH': '/usr/sbin:/sbin:' + os.environ['PATH']}

subprocess.Popen(my_command, env=my_env)

Here we end up with a copy of os.environ and overridden PATH value.

It was made possible by PEP 448 (Additional Unpacking Generalizations).

Another example. If you have a default environment (i.e. os.environ), and a dict you want to override defaults with, you can express it like this:

my_env = {**os.environ, **dict_with_env_variables}

Creating email templates with Django

From the docs, to send HTML e-mail you want to use alternative content-types, like this:

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', '[email protected]', '[email protected]'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

You'll probably want two templates for your e-mail - a plain text one that looks something like this, stored in your templates directory under email.txt:

Hello {{ username }} - your account is activated.

and an HTMLy one, stored under email.html:

Hello <strong>{{ username }}</strong> - your account is activated.

You can then send an e-mail using both those templates by making use of get_template, like this:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context

plaintext = get_template('email.txt')
htmly     = get_template('email.html')

d = Context({ 'username': username })

subject, from_email, to = 'hello', '[email protected]', '[email protected]'
text_content = plaintext.render(d)
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

Eclipse error: "The import XXX cannot be resolved"

In my case it was a broken jar in the Maven repository. Delete jar files in repository and let Maven download them again.

When I ran mvn clean install from the command line, it ran fine, but Eclipse still could not compile the code. When I ran maven install in Eclipse then I saw that Maven complained about bad jar file. So I deleted it and ran maven install again. The problem was gone.

How to extract table as text from the PDF using Python?

This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.

Here are the steps I found to work.

  1. Use pdfimages from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.

  2. Use Tesseract to detect rotation and ImageMagick mogrify to fix it.

  3. Use OpenCV to find and extract tables.

  4. Use OpenCV to find and extract each cell from the table.

  5. Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.

  6. Use Tesseract to OCR each cell.

  7. Combine the extracted text of each cell into the format you need.

I wrote a python package with modules that can help with those steps.

Repo: https://github.com/eihli/image-table-ocr

Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html

Some of the steps don't require code, they take advantage of external tools like pdfimages and tesseract. I'll provide some brief examples for a couple of the steps that do require code.

  1. Finding tables:

This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/

import cv2

def find_tables(image):
    BLUR_KERNEL_SIZE = (17, 17)
    STD_DEV_X_DIRECTION = 0
    STD_DEV_Y_DIRECTION = 0
    blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
    MAX_COLOR_VAL = 255
    BLOCK_SIZE = 15
    SUBTRACT_FROM_MEAN = -2

    img_bin = cv2.adaptiveThreshold(
        ~blurred,
        MAX_COLOR_VAL,
        cv2.ADAPTIVE_THRESH_MEAN_C,
        cv2.THRESH_BINARY,
        BLOCK_SIZE,
        SUBTRACT_FROM_MEAN,
    )
    vertical = horizontal = img_bin.copy()
    SCALE = 5
    image_width, image_height = horizontal.shape
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
    horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
    vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
    vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)

    horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
    vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))

    mask = horizontally_dilated + vertically_dilated
    contours, hierarchy = cv2.findContours(
        mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
    )

    MIN_TABLE_AREA = 1e5
    contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
    perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
    epsilons = [0.1 * p for p in perimeter_lengths]
    approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
    bounding_rects = [cv2.boundingRect(a) for a in approx_polys]

    # The link where a lot of this code was borrowed from recommends an
    # additional step to check the number of "joints" inside this bounding rectangle.
    # A table should have a lot of intersections. We might have a rectangular image
    # here though which would only have 4 intersections, 1 at each corner.
    # Leaving that step as a future TODO if it is ever necessary.
    images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
    return images
  1. Extract cells from table.

This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.

We want to identify the cells from left-to-right, top-to-bottom.

We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.

def cell_in_same_row(c1, c2):
    c1_center = c1[1] + c1[3] - c1[3] / 2
    c2_bottom = c2[1] + c2[3]
    c2_top = c2[1]
    return c2_top < c1_center < c2_bottom

orig_cells = [c for c in cells]
rows = []
while cells:
    first = cells[0]
    rest = cells[1:]
    cells_in_same_row = sorted(
        [
            c for c in rest
            if cell_in_same_row(c, first)
        ],
        key=lambda c: c[0]
    )

    row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
    rows.append(row_cells)
    cells = [
        c for c in rest
        if not cell_in_same_row(c, first)
    ]

# Sort rows by average height of their center.
def avg_height_of_center(row):
    centers = [y + h - h / 2 for x, y, w, h in row]
    return sum(centers) / len(centers)

rows.sort(key=avg_height_of_center)

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

How do I make a dotted/dashed line in Android?

What I did when I wanted to draw a dotted line is to define a drawable dash_line.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="line" >
<stroke
    android:dashGap="3dp"
    android:dashWidth="2dp"
    android:width="1dp"
    android:color="@color/black" />
</shape>

And then in the layout just define a view with background as dash_line. Note to include android:layerType="software", otherwise it won't work.

<View
            android:layout_width="match_parent"
            android:layout_height="5dp"
            android:background="@drawable/dash_line"
            android:layerType="software" />

How to get page content using cURL?

Try This:

$url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_VERBOSE, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
  curl_setopt($ch, CURLOPT_URL, urlencode($url));
  $response = curl_exec($ch);
  curl_close($ch);

Implement an input with a mask

I taken from this thread decision Implement an input with a mask and adapted it for IE10, and added setter- and getter- functions.

BUT I TESTED FOR PHONE-mask ONLY

$(document).ready(function(){
    var el_arr = document.querySelectorAll("[placeholder][data-slots]");
    for (var el_ind=0; el_ind < el_arr.length; el_ind++ ){
        var el = el_arr[el_ind];
        var pattern = el.getAttribute("placeholder"),
            slots = new Set(el.getAttribute("data-slots") || "_"),
            prev = function(j){return Array.from(pattern, function(c,i){ return slots.has(c)? j=i+1: j;});}(0),
            first = pattern.split('').findIndex(function(c){return slots.has(c);} ),
            accept = new RegExp(el.getAttribute("data-accept") || "\\d", "g"),
            clean = function(input){input = input.match(accept) || [];return Array.from(pattern, function(c){return input[0] === c || slots.has(c) ? input.shift() || c : c;});},
            format = function(){
                var elem = this;
                var i_j_arr = [el.selectionStart, el.selectionEnd].map(function(i){
                    i = clean(el.value.slice(0, i)).findIndex(function(c){ return slots.has(c);});
                    return i<0? prev[prev.length-1]: elem.back? prev[i-1] || first: i;
                });
                el.value = clean(el.value).join('');
                el.setSelectionRange(i_j_arr[0], i_j_arr[1]);
                this.back = false;
            },
            // sdo added
            get_masked_value = function(){
                var input = this.value;
                var ret=[];
                for(var k in pattern){
                    if ( !input[k] )break;
                    if( slots.has(pattern[k]) && input[k]!=pattern[k]){
                        ret.push(input[k]);
                    } 
                } 
                return ret.join('');
            },
            set_masked_value = function(input){
                var ret=[];
                var index_in_value = 0;
                for(var k in pattern){
                    if( slots.has(pattern[k]) && input[index_in_value]){
                        ret.push(input[index_in_value]);
                        index_in_value++;
                    }
                    else{
                        ret.push(pattern[k]);
                    }
                } 
                this.value = ret.join('');
            }                    
        ;
        el.get_masked_value = get_masked_value;
        el.set_masked_value = set_masked_value;
        el.back = false;
        el.addEventListener("keydown", function(event){ this.back = event.key === "Backspace";});
        el.addEventListener("input", format);
        el.addEventListener("focus", format);
        el.addEventListener("blur", function() { return el.value === pattern && (el.value=""); });
    }

});   

"Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

Check for the 32/64 bit you trying to install. both python interpreter and your app which trying to use python might be of different bit.

Understanding the main method of python

If you import the module (.py) file you are creating now from another python script it will not execute the code within

if __name__ == '__main__':
    ...

If you run the script directly from the console, it will be executed.

Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution or importing of the module.

This is expanded upon a little more at python.berkely.edu

How to select the first, second, or third element with a given class name?

This isn't so much an answer as a non-answer, i.e. an example showing why one of the highly voted answers above is actually wrong.

I thought that answer looked good. In fact, it gave me what I was looking for: :nth-of-type which, for my situation, worked. (So, thanks for that, @Bdwey.)

I initially read the comment by @BoltClock (which says that the answer is essentially wrong) and dismissed it, as I had checked my use case, and it worked. Then I realized @BoltClock had a reputation of 300,000+(!) and has a profile where he claims to be a CSS guru. Hmm, I thought, maybe I should look a little closer.

Turns out as follows: div.myclass:nth-of-type(2) does NOT mean "the 2nd instance of div.myclass". Rather, it means "the 2nd instance of div, and it must also have the 'myclass' class". That's an important distinction when there are intervening divs between your div.myclass instances.

It took me some time to get my head around this. So, to help others figure it out more quickly, I've written an example which I believe demonstrates the concept more clearly than a written description: I've hijacked the h1, h2, h3 and h4 elements to essentially be divs. I've put an A class on some of them, grouped them in 3's, and then colored the 1st, 2nd and 3rd instances blue, orange and green using h?.A:nth-of-type(?). (But, if you're reading carefully, you should be asking "the 1st, 2nd and 3rd instances of what?"). I also interjected a dissimilar (i.e. different h level) or similar (i.e. same h level) un-classed element into some of the groups.

Note, in particular, the last grouping of 3. Here, an un-classed h3 element is inserted between the first and second h3.A elements. In this case, no 2nd color (i.e. orange) appears, and the 3rd color (i.e. green) shows up on the 2nd instance of h3.A. This shows that the n in h3.A:nth-of-type(n) is counting the h3s, not the h3.As.

Well, hope that helps. And thanks, @BoltClock.

_x000D_
_x000D_
div {_x000D_
  margin-bottom: 2em;_x000D_
  border: red solid 1px;_x000D_
  background-color: lightyellow;_x000D_
}_x000D_
_x000D_
h1,_x000D_
h2,_x000D_
h3,_x000D_
h4 {_x000D_
  font-size: 12pt;_x000D_
  margin: 5px;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(1),_x000D_
h2.A:nth-of-type(1),_x000D_
h3.A:nth-of-type(1) {_x000D_
  background-color: cyan;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(2),_x000D_
h2.A:nth-of-type(2),_x000D_
h3.A:nth-of-type(2) {_x000D_
  background-color: orange;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(3),_x000D_
h2.A:nth-of-type(3),_x000D_
h3.A:nth-of-type(3) {_x000D_
  background-color: lightgreen;_x000D_
}
_x000D_
<div>_x000D_
  <h1 class="A">h1.A #1</h1>_x000D_
  <h1 class="A">h1.A #2</h1>_x000D_
  <h1 class="A">h1.A #3</h1>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <h2 class="A">h2.A #1</h2>_x000D_
  <h4>this intervening element is a different type, i.e. h4 not h2</h4>_x000D_
  <h2 class="A">h2.A #2</h2>_x000D_
  <h2 class="A">h2.A #3</h2>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <h3 class="A">h3.A #1</h3>_x000D_
  <h3>this intervening element is the same type, i.e. h3, but has no class</h3>_x000D_
  <h3 class="A">h3.A #2</h3>_x000D_
  <h3 class="A">h3.A #3</h3>_x000D_
</div>
_x000D_
_x000D_
_x000D_

how to pass parameter from @Url.Action to controller function

should you pass it in this way :

public ActionResult CreatePerson(int id) //controller 
window.location.href = "@Url.Action("CreatePerson", "Person",new { @id = 1});

How to use border with Bootstrap

You can't just add a border to the span because it will break the layout because of the way width is calculate: width = border + padding + width. Since the container is 940px and the span is 940px, adding 2px border (so 4px altogether) will make it look off centered. The work around is to change the width to include the 4px border (original - 4px) or have another div inside that creates the 2px border.

JSON to PHP Array using file_get_contents

You JSON is not a valid string as P. Galbraith has told you above.

and here is the solution for it.

<?php 
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},

]',"}

]",$json);
$data = json_decode($json);

echo "<pre>";
print_r($data);
echo "</pre>";
?>

Use this code it will work for you.

When is assembly faster than C?

Point one which is not the answer.
Even if you never program in it, I find it useful to know at least one assembler instruction set. This is part of the programmers never-ending quest to know more and therefore be better. Also useful when stepping into frameworks you don't have the source code to and having at least a rough idea what is going on. It also helps you to understand JavaByteCode and .Net IL as they are both similar to assembler.

To answer the question when you have a small amount of code or a large amount of time. Most useful for use in embedded chips, where low chip complexity and poor competition in compilers targeting these chips can tip the balance in favour of humans. Also for restricted devices you are often trading off code size/memory size/performance in a way that would be hard to instruct a compiler to do. e.g. I know this user action is not called often so I will have small code size and poor performance, but this other function that look similar is used every second so I will have a larger code size and faster performance. That is the sort of trade off a skilled assembly programmer can use.

I would also like to add there is a lot of middle ground where you can code in C compile and examine the Assembly produced, then either change you C code or tweak and maintain as assembly.

My friend works on micro controllers, currently chips for controlling small electric motors. He works in a combination of low level c and Assembly. He once told me of a good day at work where he reduced the main loop from 48 instructions to 43. He is also faced with choices like the code has grown to fill the 256k chip and the business is wanting a new feature, do you

  1. Remove an existing feature
  2. Reduce the size of some or all of the existing features maybe at the cost of performance.
  3. Advocate moving to a larger chip with a higher cost, higher power consumption and larger form factor.

I would like to add as a commercial developer with quite a portfolio or languages, platforms, types of applications I have never once felt the need to dive into writing assembly. I have how ever always appreciated the knowledge I gained about it. And sometimes debugged into it.

I know I have far more answered the question "why should I learn assembler" but I feel it is a more important question then when is it faster.

so lets try once more You should be thinking about assembly

  • working on low level operating system function
  • Working on a compiler.
  • Working on an extremely limited chip, embedded system etc

Remember to compare your assembly to compiler generated to see which is faster/smaller/better.

David.

'str' object does not support item assignment in Python

As aix mentioned - strings in Python are immutable (you cannot change them inplace).

What you are trying to do can be done in many ways:

# Copy the string

foo = 'Hello'
bar = foo

# Create a new string by joining all characters of the old string

new_string = ''.join(c for c in oldstring)

# Slice and copy
new_string = oldstring[:]

tmux set -g mouse-mode on doesn't work

Just a quick heads-up to anyone else who is losing their mind right now:

https://github.com/tmux/tmux/blob/310f0a960ca64fa3809545badc629c0c166c6cd2/CHANGES#L12

so that's just

 :setw -g mouse

iCheck check if checkbox is checked

All callbacks and functions are documented here: http://fronteed.com/iCheck/#usage

$('input').iCheck('check'); — change input's state to checked
$('input').iCheck('uncheck'); — remove checked state
$('input').iCheck('toggle'); — toggle checked state
$('input').iCheck('disable'); — change input's state to disabled
$('input').iCheck('enable'); — remove disabled state
$('input').iCheck('indeterminate'); — change input's state to indeterminate
$('input').iCheck('determinate'); — remove indeterminate state
$('input').iCheck('update'); — apply input changes, which were done outside the plugin
$('input').iCheck('destroy'); — remove all traces of iCheck

Java: using switch statement with enum under subclass

Write someMethod() in this way:

public void someMethod() {

    SomeClass.AnotherClass.MyEnum enumExample = SomeClass.AnotherClass.MyEnum.VALUE_A;

    switch (enumExample) {
    case VALUE_A:
        break;
    }

}

In switch statement you must use the constant name only.

Open existing file, append a single line

using (StreamWriter w = File.AppendText("myFile.txt"))
{
  w.WriteLine("hello");
}

How can I symlink a file in Linux?

Links are basically of two types:

Symbolic links (soft): link to a symbolic path indicating the abstract location of another file

Hard links: link to the specific location of physical data.

Example 1:

ln /root/file1 /root/file2

The above is an example of a hard link where you can have a copy of your physical data.

Example 2:

ln -s /path/to/file1.txt /path/to/file2.txt

The above command will create a symbolic link to file1.txt.

If you delete a source file then you won't have anything to the destination in soft.

When you do:

ls -lai

You'll see that there is a different inode number for the symlinks.

For more details, you can read the man page of ln on your Linux OS.

How to add local .jar file dependency to build.gradle file?

The Question already has been answered in detail. I still want to add something that seems very surprising to me:

The "gradle dependencies" task does not list any file dependencies. Even though you might think so, as they have been specified in the "dependencies" block after all..

So don't rely on the output of this to check whether your referenced local lib files are working correctly.

htaccess Access-Control-Allow-Origin

Try this in the .htaccess of the external root folder :

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

And if it only concerns .js scripts you should wrap the above code inside this:

<FilesMatch "\.(js)$">
...
</FilesMatch>

How to localise a string inside the iOS info.plist file?

As RGML say, you can create an InfoPlist.strings, localize it then add your key and the value like this: "NSLocationWhenInUseUsageDescription" = "Help To locate me!";

It will add the key to your info.plist for the specified language.

Import data into Google Colaboratory

It has been solved, find details here and please use the function below: https://stackoverflow.com/questions/47212852/how-to-import-and-read-a-shelve-or-numpy-file-in-google-colaboratory/49467113#49467113

from google.colab import files
import zipfile, io, os

    def read_dir_file(case_f):
        # author: yasser mustafa, 21 March 2018  
        # case_f = 0 for uploading one File and case_f = 1 for uploading one Zipped Directory
        uploaded = files.upload()    # to upload a Full Directory, please Zip it first (use WinZip)
        for fn in uploaded.keys():
            name = fn  #.encode('utf-8')
            #print('\nfile after encode', name)
            #name = io.BytesIO(uploaded[name])
        if case_f == 0:    # case of uploading 'One File only'
            print('\n file name: ', name)
            return name
        else:   # case of uploading a directory and its subdirectories and files
            zfile = zipfile.ZipFile(name, 'r')   # unzip the directory 
            zfile.extractall()
            for d in zfile.namelist():   # d = directory
                print('\n main directory name: ', d)
                return d
    print('Done!')

How can I jump to class/method definition in Atom text editor?

This feature has been built-in into Atom editor (see: symbols-view package), but you need to generate ctags symbols file for your project GH-9, GH-20.

To do that, install ctags command (e.g. brew install ctags on macOS), then:

  1. Append, link or copy ctags-config to your ~/.ctags, example on macOS:

    ln -vs "$(find /Applications/Atom.app -name ctags-config -print -quit)" ~/.ctags
    
  2. Go to your project folder and run:

    cd your/project/directory
    ctags -R .
    
  3. Restart Atom editor.


Alternatively you can use symbol-gen package to generate ctags symbols file for your project based on the options found in .ctags file. You can install it from Atom Package Manager by: apm install symbol-gen. Then hit CMD-Alt-G to generate tags file for your project.


After following above, you can use Go To Declaration option from the context menu.

On macOS you can use also use the following keyboard shortcuts:

  • CMD-R to jump to a function/method in the current ,editor
  • Alt-CMD-Down to go to declaration.

jQuery disable a link

My fav in "checkout to edit an item and prevent -wild wild west clicks to anywhere- while in a checkout" functions

$('a').click(function(e) {
    var = $(this).attr('disabled');
    if (var === 'disabled') {
        e.preventDefault();
    }
});

So if i want that all external links in a second action toolbar should be disabled while in the "edit-mode" as described above, i'll add in the edit function

$('#actionToolbar .external').attr('disabled', true);

Link example after fire:

<a href="http://goo.gl" target="elsewhere" class="external" disabled="disabled">Google</a>

And now you CAN use disabled property for links

Cheers!

anchor jumping by using javascript

Not enough rep for a comment.

The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).

Something to bare in mind if you don't have control of the document markup (e.g. webextension).

The location based method in the selected answer can also be simplified with location.replace:

function jump(hash) { location.replace("#" + hash) }

join on multiple columns

tableB.col1 = tableA.col1 
OR tableB.col2 = tableA.col1  
OR tableB.col1 = tableA.col2  
OR tableB.col1 = tableA.col2

Remove all whitespace in a string

In addition, strip has some variations:

Remove spaces in the BEGINNING and END of a string:

sentence= sentence.strip()

Remove spaces in the BEGINNING of a string:

sentence = sentence.lstrip()

Remove spaces in the END of a string:

sentence= sentence.rstrip()

All three string functions strip lstrip, and rstrip can take parameters of the string to strip, with the default being all white space. This can be helpful when you are working with something particular, for example, you could remove only spaces but not newlines:

" 1. Step 1\n".strip(" ")

Or you could remove extra commas when reading in a string list:

"1,2,3,".strip(",")

How can I make the Android emulator show the soft keyboard?

Settings > Language & input > Current keyboard > Hardware Switch ON.
It allows you to use your physical keyboard for input while at the same time showing the soft keyboard. I just tested it on Android Lollipop and it works.

Getting Spring Application Context

Note that by storing any state from the current ApplicationContext, or the ApplicationContext itself in a static variable - for example using the singleton pattern - you will make your tests unstable and unpredictable if you're using Spring-test. This is because Spring-test caches and reuses application contexts in the same JVM. For example:

  1. Test A run and it is annotated with @ContextConfiguration({"classpath:foo.xml"}).
  2. Test B run and it is annotated with @ContextConfiguration({"classpath:foo.xml", "classpath:bar.xml})
  3. Test C run and it is annotated with @ContextConfiguration({"classpath:foo.xml"})

When Test A runs, an ApplicationContext is created, and any beans implemeting ApplicationContextAware or autowiring ApplicationContext might write to the static variable.

When Test B runs the same thing happens, and the static variable now points to Test B's ApplicationContext

When Test C runs, no beans are created as the TestContext (and herein the ApplicationContext) from Test A is resused. Now you got a static variable pointing to another ApplicationContext than the one currently holding the beans for your test.

How do I prevent Eclipse from hanging on startup?

Also look at http://www.lazylab.org/197/eclipse/eclipse-hanging-on-startup-repair-corrupt-workspace/

99% Recommended Solution works.... (i.e. Removing .snap file) But if it did not worked then we have to try to remove indexes folder and further workbench folder.

CSS styling in Django forms

This can be done using a custom template filter. Consider rendering your form this way:

<form action="/contact/" method="post">
  {{ form.non_field_errors }}
  <div class="fieldWrapper">
    {{ form.subject.errors }}
    {{ form.subject.label_tag }}
    {{ form.subject }}
    <span class="helptext">{{ form.subject.help_text }}</span>
  </div>
</form>

form.subject is an instance of BoundField which has the as_widget() method.

You can create a custom filter addclass in my_app/templatetags/myfilters.py:

from django import template

register = template.Library()

@register.filter(name='addclass')
def addclass(value, arg):
    return value.as_widget(attrs={'class': arg})

And then apply your filter:

{% load myfilters %}

<form action="/contact/" method="post">
  {{ form.non_field_errors }}
  <div class="fieldWrapper">
    {{ form.subject.errors }}
    {{ form.subject.label_tag }}
    {{ form.subject|addclass:'MyClass' }}
    <span class="helptext">{{ form.subject.help_text }}</span>
  </div>
</form>

form.subjects will then be rendered with the MyClass CSS class.

DataTable: Hide the Show Entries dropdown but keep the Search box

This is key answer to this post "bLengthChange": false, will hide the Entries Dropdown

C# List<string> to string with delimiter

You can also do this with linq if you'd like

var names = new List<string>() { "John", "Anna", "Monica" };
var joinedNames = names.Aggregate((a, b) => a + ", " + b);

Although I prefer the non-linq syntax in Quartermeister's answer and I think Aggregate might perform slower (probably more string concatenation operations).

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

Adding padding to a tkinter widget only on one side

There are multiple ways of doing that you can use either place or grid or even the packmethod.

Sample code:

from tkinter import *
root = Tk()

l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.

To place a widget to on basis of columns and rows , use the grid method:

but = Button(root, text="hello" )
but.grid(row=0, column=1)

Bootstrap 3 Horizontal and Vertical Divider

Add the right lines this way and and the horizontal borders using HR or border-bottom or .col-right-line:after. Don't forget media queries to get rid of the lines on small devices.

.col-right-line:before {
  position: absolute;
  content: " ";
  top: 0;
  right: 0;
  height: 100%;
  width: 1px;
  background-color: @color-neutral;
}

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

The configuration here is working for me:

configurations {
    customProvidedRuntime
}

dependencies {
    compile(
        // Spring Boot dependencies
    )

    customProvidedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}

war {
    classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))
}

springBoot {
    providedConfiguration = "customProvidedRuntime"
}

How to "EXPIRE" the "HSET" child key in redis?

You can. Here is an example.

redis 127.0.0.1:6379> hset key f1 1
(integer) 1
redis 127.0.0.1:6379> hset key f2 2
(integer) 1
redis 127.0.0.1:6379> hvals key
1) "1"
2) "1"
3) "2"
redis 127.0.0.1:6379> expire key 10
(integer) 1
redis 127.0.0.1:6379> hvals key
1) "1"
2) "1"
3) "2"
redis 127.0.0.1:6379> hvals key
1) "1"
2) "1"
3) "2"
redis 127.0.0.1:6379> hvals key

Use EXPIRE or EXPIREAT command.

If you want to expire specific keys in the hash older then 1 month. This is not possible. Redis expire command is for all keys in the hash. If you set daily hash key, you can set a keys time to live.

hset key-20140325 f1 1
expire key-20140325 100
hset key-20140325 f1 2

Javascript how to parse JSON array

This is my answer,

<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br> 
Last Name: <span id="lname"></span><br> 
</p> 
<script>
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
    var counter = jsonData.employees[i];
    //console.log(counter.counter_name);
    alert(counter.firstName);
}

</script>
</body>
</html>

how concatenate two variables in batch script?

You can do it without setlocal, because of the setlocal command the variable won't survive an endlocal because it was created in setlocal. In this way the variable will be defined the right way.

To do that use this code:

set var1=A

set var2=B

set AB=hi

call set newvar=%%%var1%%var2%%%

echo %newvar% 

Note: You MUST use call before you set the variable or it won't work.

How to `wget` a list of URLs in a text file?

Quick man wget gives me the following:

[..]

-i file

--input-file=file

Read URLs from a local or external file. If - is specified as file, URLs are read from the standard input. (Use ./- to read from a file literally named -.)

If this function is used, no URLs need be present on the command line. If there are URLs both on the command line and in an input file, those on the command lines will be the first ones to be retrieved. If --force-html is not specified, then file should consist of a series of URLs, one per line.

[..]

So: wget -i text_file.txt

How do you change the colour of each category within a highcharts column chart?

Add which colors you want to colors and then set colorByPoint to true.

colors: [
'#4572A7', 
'#AA4643', 
'#89A54E', 
'#80699B', 
'#3D96AE', 
'#DB843D', 
'#92A8CD', 
'#A47D7C', 
'#B5CA92'
],

plotOptions: {
    column: {
        colorByPoint: true
    }
}

demo

Reference:

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

Concatenate strings from several rows using Pandas groupby

For me the above solutions were close but added some unwanted /n's and dtype:object, so here's a modified version:

df.groupby(['name', 'month'])['text'].apply(lambda text: ''.join(text.to_string(index=False))).str.replace('(\\n)', '').reset_index()

How can I change CSS display none or block property using jQuery?

you can do it by button

<button onclick"document.getElementById('elementid').style.display = 'none or block';">

Access elements of parent window from iframe

I think the problem may be that you are not finding your element because of the "#" in your call to get it:

window.parent.document.getElementById('#target'); 

You only need the # if you are using jquery. Here it should be:

window.parent.document.getElementById('target'); 

How to do associative array/hashing in JavaScript

In C# the code looks like:

Dictionary<string,int> dictionary = new Dictionary<string,int>();
dictionary.add("sample1", 1);
dictionary.add("sample2", 2);

or

var dictionary = new Dictionary<string, int> {
    {"sample1", 1},
    {"sample2", 2}
};

In JavaScript:

var dictionary = {
    "sample1": 1,
    "sample2": 2
}

A C# dictionary object contains useful methods, like dictionary.ContainsKey()

In JavaScript, we could use the hasOwnProperty like:

if (dictionary.hasOwnProperty("sample1"))
    console.log("sample1 key found and its value is"+ dictionary["sample1"]);

What is WEB-INF used for in a Java EE web application?

You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public. Usually, JSP or facelets are found outside WEB-INF, but in this case they are easily accesssible for any user. In case you have some authorization restrictions, WEB-INF can be used for that.

WEB-INF/lib can contain 3rd party libraries which you do not want to pack at system level (JARs can be available for all the applications running on your server), but only for this particular applciation.

Generally speaking, many configurations files also go into WEB-INF.

As for WEB-INF/classes - it exists in any web-app, because that is the folder where all the compiled sources are placed (not JARS, but compiled .java files that you wrote yourself).

How to unpackage and repackage a WAR file

copy your war file to /tmp now extract the contents:

cp warfile.war /tmp
cd /tmp
unzip warfile.war
cd WEB-INF
nano web.xml (or vim or any editor you want to use)
cd ..
zip -r -u warfile.war WEB-INF

now you have in /tmp/warfile.war your file updated.

How to make an AlertDialog in Flutter?

Another easy option to show Dialog is to use stacked_services package

 _dialogService.showDialog(
      title: "Title",
      description: "Dialog message Tex",
         );
     });

Setting a WebRequest's body data

Update

See my other SO answer.


Original

var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");

string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding

request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;

var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();

Can a Byte[] Array be written to a file in C#?

Based on the first sentence of the question: "I'm trying to write out a Byte[] array representing a complete file to a file."

The path of least resistance would be:

File.WriteAllBytes(string path, byte[] bytes)

Documented here:

System.IO.File.WriteAllBytes - MSDN

How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?

There is a .tar.gz file of the Java Runtime Environment (JRE) on the Oracle website for these operations systems: Windows x86, Windows x64, Linux x86, Linux x64, Mac OS X x64, Solaris x64. See: http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html

Also there is the Java Development Kit (JDK): http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html. The Windows .tar.gz. is missing, but you can just extract the .exe file with a tool like 7zip.

I found this is very useful to make Eclipse portable. ;-)

File name without extension name VBA

To be verbose it the removal of extension is demonstrated for workbooks.. which now have a variety of extensions . . a new unsaved Book1 has no ext . works the same for files

Function WorkbookIsOpen(FWNa$, Optional AnyExt As Boolean = False) As Boolean

Dim wWB As Workbook, WBNa$, PD%
FWNa = Trim(FWNa)
If FWNa <> "" Then
    For Each wWB In Workbooks
        WBNa = wWB.Name
        If AnyExt Then
            PD = InStr(WBNa, ".")
            If PD > 0 Then WBNa = Left(WBNa, PD - 1)
            PD = InStr(FWNa, ".")
            If PD > 0 Then FWNa = Left(FWNa, PD - 1)
            '
            ' the alternative of using split..  see commented out  below
            ' looks neater but takes a bit longer then the pair of instr and left
            ' VBA does about 800,000  of these small splits/sec
            ' and about 20,000,000  Instr Lefts per sec
            ' of course if not checking for other extensions they do not matter
            ' and to any reasonable program
            ' THIS DISCUSSIONOF TIME TAKEN DOES NOT MATTER
            ' IN doing about doing 2000 of this routine per sec

            ' WBNa = Split(WBNa, ".")(0)
            'FWNa = Split(FWNa, ".")(0)
        End If

        If WBNa = FWNa Then
            WorkbookIsOpen = True
            Exit Function
        End If
    Next wWB
End If

End Function

How to encrypt and decrypt file in Android?

You could use java-aes-crypto or Facebook's Conceal

java-aes-crypto

Quoting from the repo

A simple Android class for encrypting & decrypting strings, aiming to avoid the classic mistakes that most such classes suffer from.

Facebook's conceal

Quoting from the repo

Conceal provides easy Android APIs for performing fast encryption and authentication of data

Count the number of occurrences of a character in a string in Javascript

Performance of Split vs RegExp

_x000D_
_x000D_
var i = 0;_x000D_
_x000D_
var split_start = new Date().getTime();_x000D_
while (i < 30000) {_x000D_
  "1234,453,123,324".split(",").length -1;_x000D_
  i++;_x000D_
}_x000D_
var split_end = new Date().getTime();_x000D_
var split_time = split_end - split_start;_x000D_
_x000D_
_x000D_
i= 0;_x000D_
var reg_start = new Date().getTime();_x000D_
while (i < 30000) {_x000D_
  ("1234,453,123,324".match(/,/g) || []).length;_x000D_
  i++;_x000D_
}_x000D_
var reg_end = new Date().getTime();_x000D_
var reg_time = reg_end - reg_start;_x000D_
_x000D_
alert ('Split Execution time: ' + split_time + "\n" + 'RegExp Execution time: ' + reg_time + "\n");
_x000D_
_x000D_
_x000D_

How do I create a multiline Python string with inline variables?

The common way is the format() function:

>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'

It works fine with a multi-line format string:

>>> s = '''\
... This is a {length} example.
... Here is a {ordinal} line.\
... '''.format(length='multi-line', ordinal='second')
>>> print(s)
This is a multi-line example.
Here is a second line.

You can also pass a dictionary with variables:

>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'

The closest thing to what you asked (in terms of syntax) are template strings. For example:

>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'

I should add though that the format() function is more common because it's readily available and it does not require an import line.

How Can I Override Style Info from a CSS Class in the Body of a Page?

  • Id's are prior to classnames.
  • Tag attribue 'style=' is prior to CSS selectors.
  • !important word is prior to first two rules.
  • More specific CSS selectors are prior to less specific. More specific will be applied.

for example:

  • .divclass .spanclass is more specific than .spanclass
  • .divclass.divclass is more specific than .divclass
  • #divId .spanclass has ID that's why it is more specific than .divClass .spanClass
  • <div id="someDiv" style="color:red;"> has attribute and beats #someDiv{color:blue}
  • style: #someDiv{color:blue!important} will be applied over attribute style="color:red"

Git - How to close commit editor?

You Just clicking the key.

first press ESC + enter and then press :x + enter

MySQL: selecting rows where a column is null

SQL NULL's special, and you have to do WHERE field IS NULL, as NULL cannot be equal to anything,

including itself (ie: NULL = NULL is always false).

See Rule 3 https://en.wikipedia.org/wiki/Codd%27s_12_rules

What is the difference between Trap and Interrupt?

A trap is called by code like programs and used e. g. to call OS routines (i. e. normally synchronous). An interrupt is called by events (many times hardware, like the network card having received data, or the CPU timer), and - as the name suggests - interrupts the normal control flow, as the CPU has to switch to the driver routine to handle the event.

Disable vertical sync for glxgears

For Intel graphics and AMD/ATI opensource graphics drivers

Find the "Device" section of /etc/X11/xorg.conf which contains one of the following directives:

  • Driver "intel"
  • Driver "radeon"
  • Driver "fglrx"

And add the following line to that section:

Option     "SwapbuffersWait"       "false"

And run your application with vblank_mode environment variable set to 0:

$ vblank_mode=0 glxgears

For Nvidia graphics with the proprietary Nvidia driver

$ echo "0/SyncToVBlank=0" >> ~/.nvidia-settings-rc

The same change can be made in the nvidia-settings GUI by unchecking the option at X Screen 0 / OpenGL Settings / Sync to VBlank. Or, if you'd like to just test the setting without modifying your ~/.nvidia-settings-rc file you can do something like:

$ nvidia-settings --load-config-only --assign="SyncToVBlank=0"  # disable vertical sync
$ glxgears  # test it out
$ nvidia-settings --load-config-only  # restore your original vertical sync setting

How to extract HTTP response body from a Python requests call?

Your code is correct. I tested:

r = requests.get("http://www.google.com")
print(r.content)

And it returned plenty of content. Check the url, try "http://www.google.com". Cheers!

How to hide .php extension in .htaccess

1) Are you sure mod_rewrite module is enabled? Check phpinfo()

2) Your above rule assumes the URL starts with "folder". Is this correct? Did you acutally want to have folder in the URL? This would match a URL like:

/folder/thing -> /folder/thing.php

If you actually want

/thing -> /folder/thing.php

You need to drop the folder from the match expression.

I usually use this to route request to page without php (but yours should work which leads me to think that mod_rewrite may not be enabled):

RewriteRule ^([^/\.]+)/?$ $1.php  [L,QSA]

3) Assuming you are declaring your rules in an .htaccess file, does your installation allow for setting Options (AllowOverride) overrides in .htaccess files? Some shared hosts do not.

When the server finds an .htaccess file (as specified by AccessFileName) it needs to know which directives declared in that file can override earlier access information.

VB.NET - If string contains "value1" or "value2"

You need this

If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
    'Code
End if

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

Finally I can fix the issue now.

At first, we need to identify or understand the problem which mostly people not really findout, my VM is came with guest OS of Ubuntu 64-bits but after import, we check on that VM it shows only 32-bits OS.

When we start the VM, we got error as:

Failed to open a session for the virtual machine ERPNext-Develop-20180331192506.

Raw-mode is unavailable courtesy of Hyper-V. (VERR_SUPDRV_NO_RAW_MODE_HYPER_V_ROOT).

Result Code: E_FAIL (0x80004005)
Component: ConsoleWrap
Interface: IConsole {872da645-4a9b-1727-bee2-5585105b9eed}

I did try above solutions, somehow not really work or I might miss something.

Then I notice the point above (32-bits OS) so I think the problem might be with this one.

With some posts around the Internet, it could explain that Windows 10 also comes with the Hyper-V which is conflict with Oracle VM VirtualBox.

So solution I did...

1. Disable Virtualization Based Security in group policy

  • Start Run application and start: gpedit.msc
  • Go to Computer configuration > Administrative Template > Device Guard

enter image description here

  1. Disable Microsoft Hyper-V

    • Start Run application and start: OptionalFeatures.exe
    • Untick: Hyper-V
    • Restart the PC

enter image description here

Then we can use the VM, it's started. Among the two steps above, I believe that step 2 is really solved.

Anyway, please try it and let's know if it helps.

How to declare a variable in a PostgreSQL query

I accomplished the same goal by using a WITH clause, it's nowhere near as elegant but can do the same thing. Though for this example it's really overkill. I also don't particularly recommend this.

WITH myconstants (var1, var2) as (
   values (5, 'foo')
)
SELECT *
FROM somewhere, myconstants
WHERE something = var1
   OR something_else = var2;

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

How about using Postgres built-in array functions? At least on 8.4 this works out of the box:

SELECT company_id, array_to_string(array_agg(employee), ',')
FROM mytable
GROUP BY company_id;

Returning boolean if set is empty

If c is a set then you can check whether it's empty by doing: return not c.

If c is empty then not c will be True.

Otherwise, if c contains any elements not c will be False.

How to prevent text in a table cell from wrapping

<th nowrap="nowrap">

or

<th style="white-space:nowrap;">

or

<th class="nowrap">
<style type="text/css">
.nowrap { white-space: nowrap; }
</style>

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

I was able to resolve the same problem with maven-antrun-plugin and jaxb2-maven-plugin in Eclipse Kepler 4.3 by appying this solution: http://wiki.eclipse.org/M2E_plugin_execution_not_covered#Eclipse_4.2_add_default_mapping
So the content of my %elipse_workspace_name%/.metadata/.plugins/org.eclipse.m2e.core/lifecycle-mapping-metadata.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<lifecycleMappingMetadata>
  <pluginExecutions>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <versionRange>1.3</versionRange>
        <goals>
          <goal>run</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore />
      </action>
    </pluginExecution>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxb2-maven-plugin</artifactId>
        <versionRange>1.2</versionRange>
        <goals>
          <goal>xjc</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore />
      </action>
    </pluginExecution>
  </pluginExecutions>
</lifecycleMappingMetadata>

*Had to restart Eclipse to see the errors gone.

Sending simple message body + file attachment using Linux Mailx

You can try this:

(cat ./body.txt)|mailx -s "subject text" -a "attchement file" [email protected]

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

Abort a git cherry-pick?

I found the answer is git reset --merge - it clears the conflicted cherry-pick attempt.

Javascript: console.log to html

Create an ouput

<div id="output"></div>

Write to it using JavaScript

var output = document.getElementById("output");
output.innerHTML = "hello world";

If you would like it to handle more complex output values, you can use JSON.stringify

var myObj = {foo: "bar"};
output.innerHTML = JSON.stringify(myObj);

Unable to set data attribute using jQuery Data() API

Happened the same to me. It turns out that

var data = $("#myObject").data();

gives you a non-writable object. I solved it using:

var data = $.extend({}, $("#myObject").data());

And from then on, data was a standard, writable JS object.

What exactly is LLVM?

LLVM is a library that is used to construct, optimize and produce intermediate and/or binary machine code.

LLVM can be used as a compiler framework, where you provide the "front end" (parser and lexer) and the "back end" (code that converts LLVM's representation to actual machine code).

LLVM can also act as a JIT compiler - it has support for x86/x86_64 and PPC/PPC64 assembly generation with fast code optimizations aimed for compilation speed.

Unfortunately disabled since 2013, there was the ability to play with LLVM's machine code generated from C or C++ code at the demo page.

R solve:system is exactly singular

Using solve with a single parameter is a request to invert a matrix. The error message is telling you that your matrix is singular and cannot be inverted.

Get root view from current activity

Kotlin Extension Solution

Use this to simplify access in an Activity. Then you can directly refer to rootView from the Activity, or activity.rootView outside of it:

val Activity.rootView get() = window.decorView.rootView

If you'd like to add the same for Fragments for consistency, add:

val Fragment.rootView get() = view?.rootView

JavaScript - Getting HTML form values

document.forms will contain an array of forms on your page. You can loop through these forms to find the specific form you desire.

var form = false;
var length = document.forms.length;
for(var i = 0; i < length; i++) {
    if(form.id == "wanted_id") {
        form = document.forms[i];
    }
}

Each form has an elements array which you can then loop through to find the data that you want. You should also be able to access them by name

var wanted_value = form.someFieldName.value;
jsFunction(wanted_value);

Stripping everything but alphanumeric chars from a string in Python

If i understood correctly the easiest way is to use regular expression as it provides you lots of flexibility but the other simple method is to use for loop following is the code with example I also counted the occurrence of word and stored in dictionary..

s = """An... essay is, generally, a piece of writing that gives the author's own 
argument — but the definition is vague, 
overlapping with those of a paper, an article, a pamphlet, and a short story. Essays 
have traditionally been 
sub-classified as formal and informal. Formal essays are characterized by "serious 
purpose, dignity, logical 
organization, length," whereas the informal essay is characterized by "the personal 
element (self-revelation, 
individual tastes and experiences, confidential manner), humor, graceful style, 
rambling structure, unconventionality 
or novelty of theme," etc.[1]"""

d = {}      # creating empty dic      
words = s.split() # spliting string and stroing in list
for word in words:
    new_word = ''
    for c in word:
        if c.isalnum(): # checking if indiviual chr is alphanumeric or not
            new_word = new_word + c
    print(new_word, end=' ')
    # if new_word not in d:
    #     d[new_word] = 1
    # else:
    #     d[new_word] = d[new_word] +1
print(d)

please rate this if this answer is useful!

NotificationCompat.Builder deprecated in Android O

Here is the sample code, which is working in Android Oreo and less than Oreo.

  NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
                notificationManager.createNotificationChannel(notificationChannel);
                builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
            } else {
                builder = new NotificationCompat.Builder(getApplicationContext());
            }

            builder = builder
                    .setSmallIcon(R.drawable.ic_notification_icon)
                    .setColor(ContextCompat.getColor(context, R.color.color))
                    .setContentTitle(context.getString(R.string.getTitel))
                    .setTicker(context.getString(R.string.text))
                    .setContentText(message)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true);
            notificationManager.notify(requestCode, builder.build());

how to fetch data from database in Hibernate

The correct way from hibernate doc:

    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {

        tx = s.beginTransaction();        

        // here get object
        List<Employee> list = s.createCriteria(Employee.class).list();

        tx.commit();

    } catch (HibernateException ex) {
        if (tx != null) {
            tx.rollback();
        }            
        Logger.getLogger("con").info("Exception: " + ex.getMessage());
        ex.printStackTrace(System.err);
    } finally {
        s.close(); 
    }

HibernateUtil code (can find at Google):

            public class HibernateUtil {

                private static final SessionFactory tmrSessionFactory;
                private static final Ejb3Configuration tmrEjb3Config;
                private static final EntityManagerFactory tmrEntityManagerFactory;

                static {

                    try {

                        tmrSessionFactory = new Configuration().configure("tmr.cfg.xml").buildSessionFactory();
                        tmrEjb3Config = new Ejb3Configuration().configure("tmr.cfg.xml");
                        tmrEntityManagerFactory = tmrEjb3Config.buildEntityManagerFactory();

                    } catch (HibernateException ex) {
                        Logger.getLogger("app").log(Level.WARN, ex.getMessage());
                        throw new ExceptionInInitializerError(ex);
                    }
                }

                public static SessionFactory getSessionFactory() {
                    return tmrSessionFactory;
                }

                /* getters and setters here */


            }

Signed versus Unsigned Integers

Unsigned can hold a larger positive value and no negative value.

Yes.

Unsigned uses the leading bit as a part of the value, while the signed version uses the left-most-bit to identify if the number is positive or negative.

There are different ways of representing signed integers. The easiest to visualise is to use the leftmost bit as a flag (sign and magnitude), but more common is two's complement. Both are in use in most modern microprocessors — floating point uses sign and magnitude, while integer arithmetic uses two's complement.

Signed integers can hold both positive and negative numbers.

Yes.

Where does MAMP keep its php.ini?

Note: If this doesn't help, check below for Ricardo Martins' answer.


Create a PHP script with <?php phpinfo() ?> in it, run that from your browser, and look for the value Loaded Configuration File. This tells you which php.ini file PHP is using in the context of the web server.

"Fade" borders in CSS

I know this is old but this seems to work well for me in 2020...

Using the border-image CSS property I was able to quickly manipulate the borders for this fading purpose.

Note: I don't think border-image works well with border-radius... I seen someone saying that somewhere but for this purpose it works well.

1 Liner:

CSS

 .bbdr_rfade_1      { border: 4px solid; border-image: linear-gradient(90deg, rgba(60,74,83,0.90), rgba(60,74,83,.00)) 1; border-left:none; border-top:none; border-right:none;  }

HTML

<div class = 'bbdr_rfade_1'>Oh I am so going to not up-vote this guy...</div>

How to compare DateTime without time via LINQ?

It happens that LINQ doesn't like properties such as DateTime.Date. It just can't convert to SQL queries. So I figured out a way of comparing dates using Jon's answer, but without that naughty DateTime.Date. Something like this:

var q = db.Games.Where(t => t.StartDate.CompareTo(DateTime.Today) >= 0).OrderBy(d => d.StartDate);

This way, we're comparing a full database DateTime, with all that date and time stuff, like 2015-03-04 11:49:45.000 or something like this, with a DateTime that represents the actual first millisecond of that day, like 2015-03-04 00:00:00.0000.

Any DateTime we compare to that DateTime.Today will return us safely if that date is later or the same. Unless you want to compare literally the same day, in which case I think you should go for Caesar's answer.

The method DateTime.CompareTo() is just fancy Object-Oriented stuff. It returns -1 if the parameter is earlier than the DateTime you referenced, 0 if it is LITERALLY EQUAL (with all that timey stuff) and 1 if it is later.

How to get element value in jQuery

Use .text() or .html()

$("#list li").click(function() {
        var selected = $(this).text();
        alert(selected);
});

Finding the average of a list

I had a similar question to solve in a Udacity´s problems. Instead of a built-in function i coded:

def list_mean(n):

    summing = float(sum(n))
    count = float(len(n))
    if n == []:
        return False
    return float(summing/count)

Much more longer than usual but for a beginner its quite challenging.

'router-outlet' is not a known element

Try this:

Import RouterModule into your app.module.ts

import { RouterModule } from '@angular/router';

Add RouterModule into your imports []

like this:

 imports: [    RouterModule,  ]

Deserialize JSON into C# dynamic object?

For that I would use JSON.NET to do the low-level parsing of the JSON stream and then build up the object hierarchy out of instances of the ExpandoObject class.

Get the last insert id with doctrine 2?

You can access the id after calling the persist method of the entity manager.

$widgetEntity = new WidgetEntity();
$entityManager->persist($widgetEntity);
$entityManager->flush();
$widgetEntity->getId();

You do need to flush in order to get this id.

Syntax Error Fix: Added semi-colon after $entityManager->flush() is called.

Database design for a survey

The second approach is best.

If you want to normalize it further you could create a table for question types

The simple things to do are:

  • Place the database and log on their own disk, not all on C as default
  • Create the database as large as needed so you do not have pauses while the database grows

We have had log tables in SQL Server Table with 10's of millions rows.

What is the opposite of :hover (on mouse leave)?

Put your duration time in the non-hover selection:

li a {
  background-color: #111;
  transition:1s;
}

li a:hover {
  padding:19px;
}

Java: Convert String to TimeStamp

first convert your date string to date then convert it to timestamp by using following set of line

Date date=new Date();
Timestamp timestamp = new Timestamp(date.getTime());//instead of date put your converted date
Timestamp myTimeStamp= timestamp;

Force to open "Save As..." popup open at text link click for PDF in HTML

Use the download attribute, but take into account that it only works for files hosted in the same origin that your code. It means that users can only download files that are from the origin site, same host.

Download with original filename:

<a href="file link" download target="_blank">Click here to download</a>

Download with 'some_name' as filename:

<a href="file link" download="some_name" target="_blank">Click here to download</a>

Adding target="_blank" we will use a new Tab instead of the actual one, and also it will contribute to the proper behavior of the download attribute in some scenarios.

It follows the same rules as same-origin policy. You can learn more about this policy on the MDN Web Doc same-origin policy page

You can lern more about this download HTML5 attribute on the MDN Web Doc anchor's attributes page.

What's the difference between TRUNCATE and DELETE in SQL

I'd comment on matthieu's post, but I don't have the rep yet...

In MySQL, the auto increment counter gets reset with truncate, but not with delete.

Getting "TypeError: failed to fetch" when the request hasn't actually failed

If your are invoking fetch on a localhost server, use non-SSL unless you have a valid certificate for localhost. fetch will fail on an invalid or self signed certificate especially on localhost.

How to show form input fields based on select value?

You have a few issues with your code:

  1. you are missing an open quote on the id of the select element, so: <select name="dbType" id=dbType">

should be <select name="dbType" id="dbType">

  1. $('this') should be $(this): there is no need for the quotes inside the paranthesis.

  2. use .val() instead of .value() when you want to retrieve the value of an option

  3. when u initialize "selection" do it with a var in front of it, unless you already have done it at the beggining of the function

try this:

   $('#dbType').on('change',function(){
        if( $(this).val()==="other"){
        $("#otherType").show()
        }
        else{
        $("#otherType").hide()
        }
    });

http://jsfiddle.net/ks6cv/

UPDATE for use with switch:

$('#dbType').on('change',function(){
     var selection = $(this).val();
    switch(selection){
    case "other":
    $("#otherType").show()
   break;
    default:
    $("#otherType").hide()
    }
});

UPDATE with links for jQuery and jQuery-UI:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>??

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Using this HTML:

<div id="myElement" style="position: absolute">This stays at the top</div>

This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.

$(window).scroll(function() {
    $('#myElement').css('top', $(this).scrollTop() + "px");
});

As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's debounce/throttle plugin to reduce overhead.

Generate Json schema from XML schema (XSD)

True, but after turning json to xml with xmlspy, you can use trang application (http://www.thaiopensource.com/relaxng/trang.html) to create an xsd from xml file(s).

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

I had the same problem: The address shown in Preferences -> Sharing -> Remote Login didn't work and I got a '... nodename nor servname provided, or not known'. However, when I manually edited the settings (in Preferences -> Sharing -> Remote Login -> edit) and enabled "Use dynamic global hostname", it suddenly worked.

enter image description here

enter image description here

CSS background-image not working

In addition to display:block OR display:inline-block

Try giving sufficient padding to your .btn-pToolName and make sure you have the correct values for background-position

Numpy AttributeError: 'float' object has no attribute 'exp'

Probably there's something wrong with the input values for X and/or T. The function from the question works ok:

import numpy as np
from math import e

def sigmoid(X, T):
  return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))

X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])

print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))

Result:

[[15 16]
 [ 5 10]]

[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]

[[ 0.99999969  0.99999989]
 [ 0.99330715  0.9999546 ]]

Probably it's the dtype of your input arrays. Changing X to:

X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)

Gives:

Traceback (most recent call last):
  File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
    print sigmoid(X, T)
  File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
    return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp

Limiting number of displayed results when using ngRepeat

This works better in my case if you have object or multi-dimensional array. It will shows only first items, other will be just ignored in loop.

.filter('limitItems', function () {
  return function (items) {
    var result = {}, i = 1;
    angular.forEach(items, function(value, key) {
      if (i < 5) {
        result[key] = value;
      }
      i = i + 1;
    });
    return result;
  };
});

Change 5 on what you want.