Programs & Examples On #Routedevent

A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event.

Error: the entity type requires a primary key

Make sure you have the following condition:

  1. Use [key] if your primary key name is not Id or ID.
  2. Use the public keyword.
  3. Primary key should have getter and setter.

Example:

public class MyEntity {
   [key]
   public Guid Id {get; set;}
}

Calling async method on button click

use below code

 Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));

How to resolve Value cannot be null. Parameter name: source in linq?

Value cannot be null. Parameter name: source

Above error comes in situation when you are querying the collection which is null.

For demonstration below code will result in such an exception.

Console.WriteLine("Hello World");
IEnumerable<int> list = null;
list.Where(d => d ==4).FirstOrDefault();

Here is the output of the above code.

Hello World Run-time exception (line 11): Value cannot be null. Parameter name: source

Stack Trace:

[System.ArgumentNullException: Value cannot be null. Parameter name: source] at Program.Main(): line 11

In your case ListMetadataKor is null. Here is the fiddle if you want to play around.

How to resolve this System.IO.FileNotFoundException

Check all the references carefully

  • Version remains same on target machine and local machine
  • If assembly is referenced from GAC, ensure that proper version is loaded

For me cleaning entire solution by deleting manually, updating (removing and adding) references again with version in sync with target machine and then building with with Copy Local > False for GAC assemblies solves the problem.

How to upload file to server with HTTP POST multipart/form-data?

Top to @loop answer.

We got below error for Asp.Net MVC, Unable to connect to the remote server

Fix: After adding the below code in Web.Confing issue has been resolved for us

  <system.net>
    <defaultProxy useDefaultCredentials="true" >
    </defaultProxy>
  </system.net>

Where do I mark a lambda expression async?

To mark a lambda async, simply prepend async before its argument list:

// Add a command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", async (contextMenuCmd) =>
{
    SQLiteUtils slu = new SQLiteUtils();
    await slu.DeleteGroupAsync(groupName);
}));

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

If the radiobutton-checked event occurs before the content of the window is loaded fully, i.e. the ellipse is loaded fully, such an exception will be thrown. So check if the UI of the window is loaded (probably by Window_ContentRendered event, etc.).

Task<> does not contain a definition for 'GetAwaiter'

GetAwaiter(), that is used by await, is implemented as an extension method in the Async CTP. I'm not sure what exactly are you using (you mention both the Async CTP and VS 2012 RC in your question), but it's possible the Async targeting pack uses the same technique.

The problem then is that extension methods don't work with dynamic. What you can do is to explicitly specify that you're working with a Task, which means the extension method will work, and then switch back to dynamic:

private async void MyButtonClick(object sender, RoutedEventArgs e)
{
    dynamic request = new SerializableDynamicObject();
    request.Operation = "test";

    Task<SerializableDynamicObject> task = Client(request);
    dynamic result = await task;

    // use result here
}

Or, since the Client() method is actually not dynamic, you could call it with SerializableDynamicObject, not dynamic, and so limit using dynamic as much as possible:

private async void MyButtonClick(object sender, RoutedEventArgs e)
{
    var request = new SerializableDynamicObject();
    dynamic dynamicRequest = request;
    dynamicRequest.Operation = "test";

    var task = Client(request);
    dynamic result = await task;

    // use result here
}

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

How to call a button click event from another method

Usually the better way is to trigger an event (click) instead of calling the method directly.

How to update UI from another thread running in another class

Thank God, Microsoft got that figured out in WPF :)

Every Control, like a progress bar, button, form, etc. has a Dispatcher on it. You can give the Dispatcher an Action that needs to be performed, and it will automatically call it on the correct thread (an Action is like a function delegate).

You can find an example here.

Of course, you'll have to have the control accessible from other classes, e.g. by making it public and handing a reference to the Window to your other class, or maybe by passing a reference only to the progress bar.

Updating GUI (WPF) using a different thread

You need to use Dispatcher.BeginInvoke. I did not test it but you can check this link(this is the same link provided by Julio G) to have better understanding on how to update the UI controls from different thread. I have modified your ReadData() code

public void ReadData()
{
    int counter = 0;

    while (SerialData.IsOpen)
    {
        if (counter == 0)
        {
            //try
            //{
                InputSpeed = Convert.ToInt16(SerialData.ReadChar());
                CurrentSpeed = InputSpeed;
                if (CurrentSpeed > MaximumSpeed)
                {
                    MaximumSpeed = CurrentSpeed;
                }
    SpeedTextBox.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
        new Action(delegate() { SpeedTextBox.Text = "Current Wheel Speed = " + Convert.ToString(CurrentSpeed) + "Km/h"; });//update GUI from this thread


                DistanceTravelled = DistanceTravelled + (Convert.ToInt16(CurrentSpeed) * Time);

    DistanceTravelledTextBox.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
        new Action(delegate() {DistanceTravelledTextBox.Text = "Total Distance Travelled = " + Convert.ToString(DistanceTravelled) + "Km"; });//update GUI from this thread

            //}
            //catch (Exception) { }
        }
        if (counter == 1)
        {
            try
            {
                RiderInput = Convert.ToInt16(SerialData.ReadLine());
                if (RiderInput > maximumRiderInput)
                {
                    maximumRiderInput = RiderInput;
                }                       
    RiderInputTextBox.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, 
        new Action(delegate() { RiderInputTextBox.Text = "Current Rider Input Power =" + Convert.ToString(RiderInput) + "Watts"; });//update GUI from this thread
            }
            catch (Exception) { }
        }
        if (counter == 2)
        {
            try
            {
                MotorOutput = Convert.ToInt16(SerialData.ReadLine());
                if (MotorOutput > MaximumMotorOutput)
                {
                    MaximumMotorOutput = MotorOutput;
                }
    MotorOutputTextBox.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, 
        new Action(delegate() { MotorOutputTextBox.Text = "Current Motor Output = " + Convert.ToString(MotorOutput) + "Watts"; });//update GUI from this thread                        
            }
            catch (Exception) { }
        }
        counter++;
        if (counter == 3)
        {
            counter = 0;
        }
    }
}

How to remove all ListBox items?

while (listBox1.Items.Count > 0){ 
    listBox1.Items.Remove(0);
}

Setting a property with an EventTrigger

Stopping the Storyboard can be done in the code behind, or the xaml, depending on where the need comes from.

If the EventTrigger is moved outside of the button, then we can go ahead and target it with another EventTrigger that will tell the storyboard to stop. When the storyboard is stopped in this manner it will not revert to the previous value.

Here I've moved the Button.Click EventTrigger to a surrounding StackPanel and added a new EventTrigger on the the CheckBox.Click to stop the Button's storyboard when the CheckBox is clicked. This lets us check and uncheck the CheckBox when it is clicked on and gives us the desired unchecking behavior from the button as well.

    <StackPanel x:Name="myStackPanel">

        <CheckBox x:Name="myCheckBox"
                  Content="My CheckBox" />

        <Button Content="Click to Uncheck"
                x:Name="myUncheckButton" />

        <Button Content="Click to check the box in code."
                Click="OnClick" />

        <StackPanel.Triggers>

            <EventTrigger RoutedEvent="Button.Click"
                          SourceName="myUncheckButton">
                <EventTrigger.Actions>
                    <BeginStoryboard x:Name="myBeginStoryboard">
                        <Storyboard x:Name="myStoryboard">
                            <BooleanAnimationUsingKeyFrames Storyboard.TargetName="myCheckBox"
                                                            Storyboard.TargetProperty="IsChecked">
                                <DiscreteBooleanKeyFrame KeyTime="00:00:00"
                                                         Value="False" />
                            </BooleanAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>

            <EventTrigger RoutedEvent="CheckBox.Click"
                          SourceName="myCheckBox">
                <EventTrigger.Actions>
                    <StopStoryboard BeginStoryboardName="myBeginStoryboard" />
                </EventTrigger.Actions>
            </EventTrigger>

        </StackPanel.Triggers>
    </StackPanel>

To stop the storyboard in the code behind, we will have to do something slightly different. The third button provides the method where we will stop the storyboard and set the IsChecked property back to true through code.

We can't call myStoryboard.Stop() because we did not begin the Storyboard through the code setting the isControllable parameter. Instead, we can remove the Storyboard. To do this we need the FrameworkElement that the storyboard exists on, in this case our StackPanel. Once the storyboard is removed, we can once again set the IsChecked property with it persisting to the UI.

    private void OnClick(object sender, RoutedEventArgs e)
    {
        myStoryboard.Remove(myStackPanel);
        myCheckBox.IsChecked = true;
    }

Dynamic loading of images in WPF

In code to load resource in the executing assembly where my image 'Freq.png' was in the folder "Icons" and defined as "Resource".

        this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
             + Assembly.GetExecutingAssembly().GetName().Name 
             + ";component/" 
             + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function if anybody would like it...

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage:

        this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

How to open a WPF Popup when another control is clicked, using XAML markup only?

The following uses EventTrigger to show the Popup. This means we don't need a ToggleButton for state binding. In this example the Click event of a Button is used. You can adapt it to use another element/event combination.

<Button x:Name="OpenPopup">Popup
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
            <EventTrigger.Actions>
                <BeginStoryboard>
                    <Storyboard>
                        <BooleanAnimationUsingKeyFrames 
                                 Storyboard.TargetName="ContextPopup" 
                                 Storyboard.TargetProperty="IsOpen">
                            <DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True" />
                        </BooleanAnimationUsingKeyFrames>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger.Actions>
        </EventTrigger>
    </Button.Triggers>
</Button>
<Popup x:Name="ContextPopup"
       PlacementTarget="{Binding ElementName=OpenPopup}"
       StaysOpen="False">
    <Label>Popupcontent...</Label>
</Popup>

Please note that the Popup is referencing the Button by name and vice versa. So x:Name="..." is required on both, the Popup and the Button.

It can actually be further simplified by replacing the Storyboard stuff with a custom SetProperty EventTrigger Action described in this SO Answer

WPF User Control Parent

I'll add my experience. Although using the Loaded event can do the job, I think it may be more suitable to override the OnInitialized method. Loaded occurs after the window is first displayed. OnInitialized gives you chance to make any changes, for example, add controls to the window before it is rendered.

Implement a simple factory pattern with Spring 3 annotations

Why not add the interface FactoryBean to MyServiceFactory (to tell Spring that it's a factory), add a register(String service, MyService instance) then, have each of the services call:

@Autowired
MyServiceFactory serviceFactory;

@PostConstruct
public void postConstruct() {
    serviceFactory.register(myName, this);
}

This way, you can separate each service provider into modules if necessary, and Spring will automagically pick up any deployed and available service providers.

Bootstrap datepicker disabling past dates without current date

Please refer to the fiddle http://jsfiddle.net/Ritwika/gsvh83ry/

**With three fields having date greater than the **
<input type="text" type="text" class="form-control datepickstart" />
<input type="text" type="text" class="form-control datepickend" />
<input type="text" type="text" class="form-control datepickthird" />

var date = new Date();
 date.setDate(date.getDate()-1);
$('.datepickstart').datepicker({
 autoclose: true,
 todayHighlight: true,
 format: 'dd/mm/yyyy',
  startDate: date
});
$('.datepickstart').datepicker().on('changeDate', function() {
    var temp = $(this).datepicker('getDate');
    var d = new Date(temp);
  d.setDate(d.getDate() + 1);
  $('.datepickend').datepicker({
 autoclose: true,
 format: 'dd/mm/yyyy',
 startDate: d
}).on('changeDate', function() {
    var temp1 = $(this).datepicker('getDate');
    var d1 = new Date(temp1);
   d1.setDate(d1.getDate() + 1);
  $('.datepickthird').datepicker({
 autoclose: true,
 format: 'dd/mm/yyyy',
 startDate: d1
});
});
});

org.hibernate.MappingException: Unknown entity: annotations.Users

Check the package name is given in the property packagesToScan in the dispatcher-servlet.xml

<bean id="sessionFactory"             class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <property name="packagesToScan" value="**entity package name here**"></property> 
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
            </props>  
        </property>  
    </bean>

What does $1 [QSA,L] mean in my .htaccess file?

This will capture requests for files like version, release, and README.md, etc. which should be treated either as endpoints, if defined (as in the case of /release), or as "not found."

Get the _id of inserted document in Mongo database in NodeJS

@JSideris, sample code for getting insertedId.

db.collection(COLLECTION).insertOne(data, (err, result) => {
    if (err) 
      return err;
    else 
      return result.insertedId;
  });

c# Best Method to create a log file

You can use http://logging.apache.org/ library and use a database appender to collect all your log info together.

PowerShell Script to Find and Replace for all Files with a Specific Extension

When doing recursive replacement, the path and filename need to be included:

Get-ChildItem -Recurse | ForEach {  (Get-Content $_.PSPath | 
ForEach {$ -creplace "old", "new"}) | Set-Content $_.PSPath }

This wil replace all "old" with "new" case-sensitive in all the files of your folders of your current directory.

How can I get a first element from a sorted list?

Matthew's answer is correct:

list.get(0);

To do what you tried:

list[0];

you'll have to wait until Java 7 is released:

devoxx conference http://img718.imageshack.us/img718/11/capturadepantalla201003cg.png

Here's an interesting presentation by Mark Reinhold about Java 7

It looks like parleys site is currently down, try later :(

Calling a parent window function from an iframe

The solution given by Ash Clarke for subdomains works great, but please note that you need to include the document.domain = "mydomain.com"; in both the head of the iframe page and the head of the parent page, as stated in the link same origin policy checks

An important extension to the same origin policy implemented for JavaScript DOM access (but not for most of the other flavors of same-origin checks) is that two sites sharing a common top-level domain may opt to communicate despite failing the "same host" check by mutually setting their respective document.domain DOM property to the same qualified, right-hand fragment of their current host name. For example, if http://en.example.com/ and http://fr.example.com/ both set document.domain to "example.com", they would be from that point on considered same-origin for the purpose of DOM manipulation.

Passing parameters in Javascript onClick event

Try this:

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

<script language="javascript" type="text/javascript">
   var div = document.getElementById('div');

   for (var i = 0; i < 10; i++) {
       var f = function() {
           var link = document.createElement('a');
           var j = i; // this j is scoped to our anonymous function
                      // while i is scoped outside the anonymous function,
                      //  getting incremented by the for loop
           link.setAttribute('href', '#');
           link.innerHTML = j + '';
           link.onclick=  function() { onClickLink(j+'');};
           div.appendChild(link);
           div.appendChild(document.createElement('br')); // lower case BR, please!
       }(); // call the function immediately
   }

   function onClickLink(text) {
       alert('Link ' + text + ' clicked');
       return false;
   }
</script>

Python way to clone a git repository

Github's libgit2 binding, pygit2 provides a one-liner cloning a remote directory:

clone_repository(url, path, 
    bare=False, repository=None, remote=None, checkout_branch=None, callbacks=None)

Git - Undo pushed commits

Let's say 61234 is the sha-number of the last good commit you want to keep.

    git reset --hard 61234
    git push -f origin master 

? will remove completely all wrong commits without any trace.

Note: example assumed master branch on 'origin' remote.

Insert Data Into Temp Table with Query

SELECT * INTO #TempTable 
FROM SampleTable
WHERE...

SELECT * FROM #TempTable
DROP TABLE #TempTable

Return HTML from ASP.NET Web API

ASP.NET Core. Approach 1

If your Controller extends ControllerBase or Controller you can use Content(...) method:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

ASP.NET Core. Approach 2

If you choose not to extend from Controller classes, you can create new ContentResult:

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}

Legacy ASP.NET MVC Web API

Return string content with media type text/html:

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

How do I make a list of data frames?

Taking as a given you have a "large" number of data.frames with similar names (here d# where # is some positive integer), the following is a slight improvement of @mark-miller's method. It is more terse and returns a named list of data.frames, where each name in the list is the name of the corresponding original data.frame.

The key is using mget together with ls. If the data frames d1 and d2 provided in the question were the only objects with names d# in the environment, then

my.list <- mget(ls(pattern="^d[0-9]+"))

which would return

my.list
$d1
  y1 y2
1  1  4
2  2  5
3  3  6

$d2
  y1 y2
1  3  6
2  2  5
3  1  4

This method takes advantage of the pattern argument in ls, which allows us to use regular expressions to do a finer parsing of the names of objects in the environment. An alternative to the regex "^d[0-9]+$" is "^d\\d+$".

As @gregor points out, it is a better overall to set up your data construction process so that the data.frames are put into named lists at the start.

data

d1 <- data.frame(y1 = c(1,2,3),y2 = c(4,5,6))
d2 <- data.frame(y1 = c(3,2,1),y2 = c(6,5,4))

Convert hexadecimal string (hex) to a binary string

public static byte[] hexToBin(String str)
    {
        int len = str.length();
        byte[] out = new byte[len / 2];
        int endIndx;

        for (int i = 0; i < len; i = i + 2)
        {
            endIndx = i + 2;
            if (endIndx > len)
                endIndx = len - 1;
            out[i / 2] = (byte) Integer.parseInt(str.substring(i, endIndx), 16);
        }
        return out;
    }

Create a Bitmap/Drawable from file path

static ArrayList< Drawable>  d;
d = new ArrayList<Drawable>();
for(int i=0;i<MainActivity.FilePathStrings1.size();i++) {
  myDrawable =  Drawable.createFromPath(MainActivity.FilePathStrings1.get(i));
  d.add(myDrawable);
}

How do you make a div follow as you scroll?

Using styling from CSS, you can define how something is positioned. If you define the element as fixed, it will always remain in the same position on the screen at all times.

div
{
    position:fixed;
    top:20px;
}

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Use putty. Put install directory path in environment values (PATH), and restart your PC if required.

Open cmd (command prompt) and type

C:/> pscp "C:\Users/gsjha/Desktop/example.txt" user@host:/home/

It'll be copied to the system.

How to pass command-line arguments to a PowerShell ps1 file

Maybe you can wrap the PowerShell invocation in a .bat file like so:

rem ps.bat
@echo off
powershell.exe -command "%*"

If you then placed this file under a folder in your PATH, you could call PowerShell scripts like this:

ps foo 1 2 3

Quoting can get a little messy, though:

ps write-host """hello from cmd!""" -foregroundcolor green

SQL Data Reader - handling Null column values

I am using the code listed below to handle null cells in an Excel sheet that is read in to a datatable.

if (!reader.IsDBNull(2))
{
   row["Oracle"] = (string)reader[2];
}

Populate nested array in mongoose

As others have noted, Mongoose 4 supports this. It is very important to note that you can recurse deeper than one level too, if needed—though it is not noted in the docs:

Project.findOne({name: req.query.name})
    .populate({
        path: 'threads',
        populate: {
            path: 'messages', 
            model: 'Message',
            populate: {
                path: 'user',
                model: 'User'
            }
        }
    })

How to host a Node.Js application in shared hosting

I installed Node.js on bluehost.com (a shared server) using:

wget <path to download file>
tar -xf <gzip file>
mv <gzip_file_dir> node

This will download the tar file, extract to a directory and then rename that directory to the name 'node' to make it easier to use.

then

./node/bin/npm install jt-js-sample

Returns:
npm WARN engine [email protected]: wanted: {"node":"0.10.x"} (current: {"node":"0.12.4","npm":"2.10.1"})
[email protected] node_modules/jt-js-sample
+-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])

I can now use the commands:

# ~/node/bin/node -v
v0.12.4

# ~/node/bin/npm -v
2.10.1

For security reasons, I have renamed my node directory to something else.

batch file to check 64bit or 32bit OS

Here's a nice concise version:

set isX64=False && if /I "%PROCESSOR_ARCHITECTURE%"=="AMD64" ( set isX64=True ) else ( if /I "%PROCESSOR_ARCHITEW6432%"=="AMD64" ( set isX64=True ) )

echo %isX64%

Don't use the "Program Files (x86)" directory as evidence of anything: naughty software can easily create this directory on a 32-bit machine. Instead use the PROCESSOR_ARCHITECTURE and PROCESSOR_ARCHITEW6432 environment variables.

How can I find and run the keytool

Alternatively you can do the following :

  • copy the bat file below in any folder already present in your PATH environment variable
  • then simply use keytool command in any Windows shell

Actual location of keytool is defined in the bat file. In case the location is wrong the bat file will scan your system to detect potential locations in ProgramFiles (sub)folders.

Also find keytool2.bat, a convinient shortcut for "keytool -v -list -keystore", which is widely used to quickly check the content of a jks file.

keytool.bat :


:: 
:: 
:: "keytool alias" script by Céphas
:: easy method : add the known keytool.exe folder to your personal PATH variable (run : C:\Windows\System32\rundll32.exe sysdm.cpl,EditEnvironmentVariables)
:: else, add the folder containing this bat script to your personal path or put this script in any folder already defined in your path
::
:: also see keytool2.bat that automatically adds the following parameters in the keytool command line : -v -list -keystore, for quick display of jks content
:: 
:: 
@echo off
set THIS_SCRIPT=%~f0
rem  setlocal enableDelayedExpansion : necessary for paths containing special chars
setlocal enableDelayedExpansion

rem  set PATH to keytool.exe ; path must include the final \
rem  ^ is escape char for paths containing & \ < > ^ | 
set PATH_TO=C:\Program Files\Java\jre1.8.0_45\bin\
set PROG_NAME=keytool.exe

rem full_path, with "", to work with paths containing special chars
set FULL_KT_PATH="!PATH_TO!!PROG_NAME!"

rem checks if keytool.exe exists
(dir %FULL_KT_PATH%>nul 2>nul && set KT_FOUND=yes) || set KT_FOUND=no

if %KT_FOUND%==yes (
    rem keytool found => launching it with all supplied parameters
    rem 
    rem
    %FULL_KT_PATH% %*
    rem
    rem
) else (
    rem keytool not found, trying to find it in %ProgramFiles%

    echo.
    echo Keytool not found in expected location, scan in progess ...
    echo.

    cd "%ProgramFiles(x86)%" 2>nul && dir /B /S keytool.exe 2>nul

    cd "%ProgramFiles%" 2>nul && dir /B /S keytool.exe 2>nul

    echo.
    echo *********
    echo Path to program keytool.exe not properly defined, or keytool/java missing on this system
    echo If any location has been found during above scan, fix variable "PATH_TO" in %THIS_SCRIPT% accordingly
    echo *********
    echo.
    pause
    
)    

keytool2.bat :


:: 
:: 
:: "keytool2 alias" script by Céphas
:: easy method : add the known keytool.exe folder to your personal PATH variable (run : C:\Windows\System32\rundll32.exe sysdm.cpl,EditEnvironmentVariables)
:: else, add the folder containing this bat script to your personal path or put this script in any folder already defined in your path
::
:: keytool2 automatically adds the following parameters in the keytool command line : -v -list -keystore
:: thus, to quickly display the full content of a jks file, usage is simply : keytool2 \path\to\your\keystore.jks [-alias your_alias]
:: 
:: 
@echo off
set THIS_SCRIPT=%~f0
rem  setlocal enableDelayedExpansion : necessary for paths containing special chars
setlocal enableDelayedExpansion

rem  set PATH to keytool.exe ; path must include the final \
rem  ^ is escape char for paths containing & \ < > ^ | 
set PATH_TO=C:\Program Files\Java\jre1.8.0_45\bin\
set PROG_NAME=keytool.exe


rem full_path, with "", to work with paths containing special chars
set FULL_KT_PATH="!PATH_TO!!PROG_NAME!"

rem checks if keytool.exe exists
(dir %FULL_KT_PATH%>nul 2>nul && set KT_FOUND=yes) || set KT_FOUND=no

if %KT_FOUND%==yes (
    rem keytool found => launching it with all supplied parameters
    rem 
    rem
    %FULL_KT_PATH% -v -list -keystore %*
    rem
    rem
) else (
    rem keytool not found, trying to find it in %ProgramFiles%

    echo.
    echo Keytool not found in expected location, scan in progess ...
    echo.

    cd "%ProgramFiles(x86)%" 2>nul && dir /B /S keytool.exe 2>nul

    cd "%ProgramFiles%" 2>nul && dir /B /S keytool.exe 2>nul

    echo.
    echo *********
    echo Path to program keytool.exe not properly defined, or keytool/java missing on this system
    echo If any location has been found during above scan, fix variable "PATH_TO" in %THIS_SCRIPT% accordingly
    echo *********
    echo.
    pause
    
)    

Bash array with spaces in elements

I think the issue might be partly with how you're accessing the elements. If I do a simple for elem in $FILES, I experience the same issue as you. However, if I access the array through its indices, like so, it works if I add the elements either numerically or with escapes:

for ((i = 0; i < ${#FILES[@]}; i++))
do
    echo "${FILES[$i]}"
done

Any of these declarations of $FILES should work:

FILES=(2011-09-04\ 21.43.02.jpg
2011-09-05\ 10.23.14.jpg
2011-09-09\ 12.31.16.jpg
2011-09-11\ 08.43.12.jpg)

or

FILES=("2011-09-04 21.43.02.jpg"
"2011-09-05 10.23.14.jpg"
"2011-09-09 12.31.16.jpg"
"2011-09-11 08.43.12.jpg")

or

FILES[0]="2011-09-04 21.43.02.jpg"
FILES[1]="2011-09-05 10.23.14.jpg"
FILES[2]="2011-09-09 12.31.16.jpg"
FILES[3]="2011-09-11 08.43.12.jpg"

Simple pthread! C++

Because the main thread exits.

Put a sleep in the main thread.

cout << "Hello";
sleep(1);

return 0;

The POSIX standard does not specify what happens when the main thread exits.
But in most implementations this will cause all spawned threads to die.

So in the main thread you should wait for the thread to die before you exit. In this case the simplest solution is just to sleep and give the other thread a chance to execute. In real code you would use pthread_join();

#include <iostream>
#include <pthread.h>
using namespace std;

#if defined(__cplusplus)
extern "C"
#endif
void *print_message(void*)
{
    cout << "Threading\n";
}



int main() 
{
    pthread_t t1;

    pthread_create(&t1, NULL, &print_message, NULL);
    cout << "Hello";

    void* result;
    pthread_join(t1,&result);

    return 0;
}

ActionBarActivity is deprecated

According to this video of Android Developers you should only make two changes

enter image description here

Angular4 - No value accessor for form control

For me it was due to "multiple" attribute on select input control as Angular has different ValueAccessor for this type of control.

const countryControl = new FormControl();

And inside template use like this

    <select multiple name="countries" [formControl]="countryControl">
      <option *ngFor="let country of countries" [ngValue]="country">
       {{ country.name }}
      </option>
    </select>

More details ref Official Docs

Opacity of background-color, but not the text

I've created that effect on my blog Landman Code.

What I did was

_x000D_
_x000D_
#Header {
  position: relative;
}
#Header H1 {
  font-size: 3em;
  color: #00FF00;
  margin:0;
  padding:0;
}
#Header H2 {
  font-size: 1.5em;
  color: #FFFF00;
  margin:0;
  padding:0;
}
#Header .Background {
  background: #557700;
  filter: alpha(opacity=30);
  filter: progid: DXImageTransform.Microsoft.Alpha(opacity=30);
  -moz-opacity: 0.30;
  opacity: 0.3;
  zoom: 1;
}
#Header .Background * {
  visibility: hidden; // hide the faded text
}
#Header .Foreground {
  position: absolute; // position on top of the background div
  left: 0;
  top: 0;
}
_x000D_
<div id="Header">
  <div class="Background">
    <h1>Title</h1>
    <h2>Subtitle</h2>
  </div>
  <div class="Foreground">
    <h1>Title</h1>
    <h2>Subtitle</h2>
  </div>
</div>
_x000D_
_x000D_
_x000D_

The important thing that every padding/margin and content must be the same in both the .Background as .Foreground.

correct way to use super (argument passing)

If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs, and then pop them right after you use them (unless you need them in upper classes).

class First(object):
    def __init__(self, *args, **kwargs):
        self.first_arg = kwargs.pop('first_arg')
        super(First, self).__init__(*args, **kwargs)

class Second(First):
    def __init__(self, *args, **kwargs):
        self.second_arg = kwargs.pop('second_arg')
        super(Second, self).__init__(*args, **kwargs)

class Third(Second):
    def __init__(self, *args, **kwargs):
        self.third_arg = kwargs.pop('third_arg')
        super(Third, self).__init__(*args, **kwargs)

This is the simplest way to solve those kind of problems.

third = Third(first_arg=1, second_arg=2, third_arg=3)

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

PHP error: Notice: Undefined index:

apparently, the GET and/or the POST variable(s) do(es) not exist. simply test if "isset". (pseudocode):

if(isset($_GET['action'];)) {$action = $_GET['action'];} else { RECOVER FROM ERROR CODE }

VB.net Need Text Box to Only Accept Numbers

Try this:

Private Sub txtCaseID_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtCaseID.KeyPress
    If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then e.KeyChar = ""
End Sub

WampServer orange icon

If you have installed both Wampmanager and also Bitnami's wampstack on your Windows box (like I had done), make sure Bitnami has not been set to automatically start its wampstackApache and wampstackMySQL services at startup.

To check/fix this, click: Start-->Run and then type services.msc and click Ok.

Select Services in the list on the left and sort the services on Name. Scroll to the "w's". If wampstackApache and/or wampstackMySQL services are already started, right-click and stop both. Then Restart All Services from the Wampmanager W icon in the windows desktop services tray. The W should go green.

If this was your problem you can change the default startup behavior to manual start wampstackApache and wampstackMySQL in their Properties tabs.

Module is not available, misspelled or forgot to load (but I didn't)

I found this question when I got the same error for a different reason.

My issue was that my Gulp hadn't picked up on the fact that I had declared a new module and I needed to manually re-run Gulp.

How to set timeout on python's socket recv method?

You could set timeout before receiving the response and after having received the response set it back to None:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.settimeout(5.0)
data = sock.recv(1024)
sock.settimeout(None)

Sort a list alphabetically

Another way

_details.Sort((s1, s2) => s1.CompareTo(s2)); 

Redis: Show database size/size for keys

So my solution to my own problem: After playing around with redis-cli a bit longer I found out that DEBUG OBJECT <key> reveals something like the serializedlength of key, which was in fact something I was looking for...

For a whole database you need to aggregate all values for KEYS * which shouldn't be too difficult with a scripting language of your choice...

The bad thing is that redis.io doesn't really have a lot of information about DEBUG OBJECT.

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

You can use shuf. On some systems at least (doesn't appear to be in POSIX).

As jleedev pointed out: sort -R might also be an option. On some systems at least; well, you get the picture. It has been pointed out that sort -R doesn't really shuffle but instead sort items according to their hash value.

[Editor's note: sort -R almost shuffles, except that duplicate lines / sort keys always end up next to each other. In other words: only with unique input lines / keys is it a true shuffle. While it's true that the output order is determined by hash values, the randomness comes from choosing a random hash function - see manual.]

Sort Pandas Dataframe by Date

The data containing the date column can be read by using the below code:

data = pd.csv(file_path,parse_dates=[date_column])

Once the data is read by using the above line of code, the column containing the information about the date can be accessed using pd.date_time() like:

pd.date_time(data[date_column], format = '%d/%m/%y')

to change the format of date as per the requirement.

HTML5 Audio Looping

I did it this way,

<audio controls="controls" loop="loop">
<source src="someSound.ogg" type="audio/ogg" />
</audio>

and it looks like this

enter image description here

How to Git stash pop specific stash in 1.8.3?

First check the list:-

git stash list

copy the index you wanted to pop from the stash list

git stash pop stash@{index_number}

eg.:

git stash pop stash@{1}

How to check if "Radiobutton" is checked?

radiobuttonObj.isChecked() will give you boolean

if(radiobuttonObj1.isChecked()){
//do what you want 
}else if(radiobuttonObj2.isChecked()){
//do what you want 
}

Node.js – events js 72 throw er unhandled 'error' event

Well, your script throws an error and you just need to catch it (and/or prevent it from happening). I had the same error, for me it was an already used port (EADDRINUSE).

How to open warning/information/error dialog in Swing?

Just complementing: It's kind of obvious, but you can use static imports to give you a hand, like this:

import static javax.swing.JOptionPane.*;

public class SimpleDialog(){
    public static void main(String argv[]) {
        showMessageDialog(null, "Message", "Title", ERROR_MESSAGE);
    }
}

Android Overriding onBackPressed()

At first you must consider that if your activity which I called A extends another activity (B) and in both of

them you want to use onbackpressed function then every code you have in B runs in A too. So if you want to separate these you should separate them. It means that A should not extend B , then you can have onbackpressed separately for each of them.

Can't bind to 'dataSource' since it isn't a known property of 'table'

If you've tried everything mentioned here and it didn't work, make sure you also have added angular material to your project. If not, just run the following command in the terminal to add it:

ng add @angular/material

After it successfully gets added, wait for the project to get refreshed, and the error will be automatically gone.

Change / Add syntax highlighting for a language in Sublime 2/3

Syntax highlighting is controlled by the theme you use, accessible through Preferences -> Color Scheme. Themes highlight different keywords, functions, variables, etc. through the use of scopes, which are defined by a series of regular expressions contained in a .tmLanguage file in a language's directory/package. For example, the JavaScript.tmLanguage file assigns the scopes source.js and variable.language.js to the this keyword. Since Sublime Text 3 is using the .sublime-package zip file format to store all the default settings it's not very straightforward to edit the individual files.

Unfortunately, not all themes contain all scopes, so you'll need to play around with different ones to find one that looks good, and gives you the highlighting you're looking for. There are a number of themes that are included with Sublime Text, and many more are available through Package Control, which I highly recommend installing if you haven't already. Make sure you follow the ST3 directions.

As it so happens, I've developed the Neon Color Scheme, available through Package Control, that you might want to take a look at. My main goal, besides trying to make a broad range of languages look as good as possible, was to identify as many different scopes as I could - many more than are included in the standard themes. While the JavaScript language definition isn't as thorough as Python's, for example, Neon still has a lot more diversity than some of the defaults like Monokai or Solarized.

jQuery highlighted with Neon Theme

I should note that I used @int3h's Better JavaScript language definition for this image instead of the one that ships with Sublime. It can be installed via Package Control.

UPDATE

Of late I've discovered another JavaScript replacement language definition - JavaScriptNext - ES6 Syntax. It has more scopes than the base JavaScript or even Better JavaScript. It looks like this on the same code:

JavaScriptNext

Also, since I originally wrote this answer, @skuroda has released PackageResourceViewer via Package Control. It allows you to seamlessly view, edit and/or extract parts of or entire .sublime-package packages. So, if you choose, you can directly edit the color schemes included with Sublime.

ANOTHER UPDATE

With the release of nearly all of the default packages on Github, changes have been coming fast and furiously. The old JS syntax has been completely rewritten to include the best parts of JavaScript Next ES6 Syntax, and now is as fully ES6-compatible as can be. A ton of other changes have been made to cover corner and edge cases, improve consistency, and just overall make it better. The new syntax has been included in the (at this time) latest dev build 3111.

If you'd like to use any of the new syntaxes with the current beta build 3103, simply clone the Github repo someplace and link the JavaScript (or whatever language(s) you want) into your Packages directory - find it on your system by selecting Preferences -> Browse Packages.... Then, simply do a git pull in the original repo directory from time to time to refresh any changes, and you can enjoy the latest and greatest! I should note that the repo uses the new .sublime-syntax format instead of the old .tmLanguage one, so they will not work with ST3 builds prior to 3084, or with ST2 (in both cases, you should have upgraded to the latest beta or dev build anyway).

I'm currently tweaking my Neon Color Scheme to handle all of the new scopes in the new JS syntax, but most should be covered already.

Syntax error "syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)"

Just posting in case it help someone else. The cause of this error for me was a missing do after creating a form with form_with. Hope that may help someone else

Choose folders to be ignored during search in VS Code

Create a file with .gitignore & put the folder or file name which one you want to ignore.

to ignore everything below node_modules folder

echo node_modules/ > .gitignore 

How do I disable orientation change on Android?

Please note, none of the methods seems to work now!

In Android Studio 1 one simple way is to add android:screenOrientation="nosensor".

This effectively locks the screen orientation.

What does the question mark and the colon (?: ternary operator) mean in objective-c?

It's the ternary or conditional operator. It's basic form is:

condition ? valueIfTrue : valueIfFalse

Where the values will only be evaluated if they are chosen.

Converting a double to an int in C#

In the provided example your decimal is 8.6. Had it been 8.5 or 9.5, the statement i1 == i2 might have been true. Infact it would have been true for 8.5, and false for 9.5.

Explanation:

Regardless of the decimal part, the second statement, int i2 = (int)score will discard the decimal part and simply return you the integer part. Quite dangerous thing to do, as data loss might occur.

Now, for the first statement, two things can happen. If the decimal part is 5, that is, it is half way through, a decision is to be made. Do we round up or down? In C#, the Convert class implements banker's rounding. See this answer for deeper explanation. Simply put, if the number is even, round down, if the number is odd, round up.

E.g. Consider:

        double score = 8.5;
        int i1 = Convert.ToInt32(score); // 8
        int i2 = (int)score;             // 8

        score += 1;
        i1 = Convert.ToInt32(score);     // 10
        i2 = (int)score;                 // 9

How can I catch a ctrl-c event?

You have to catch the SIGINT signal (we are talking POSIX right?)

See @Gab Royer´s answer for sigaction.

Example:

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

void my_handler(sig_t s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{
   signal (SIGINT,my_handler);

   while(1);
   return 0;

}

How can I get href links from HTML using Python?

My answer probably sucks compared to the real gurus out there, but using some simple math, string slicing, find and urllib, this little script will create a list containing link elements. I test google and my output seems right. Hope it helps!

import urllib
test = urllib.urlopen("http://www.google.com").read()
sane = 0
needlestack = []
while sane == 0:
  curpos = test.find("href")
  if curpos >= 0:
    testlen = len(test)
    test = test[curpos:testlen]
    curpos = test.find('"')
    testlen = len(test)
    test = test[curpos+1:testlen]
    curpos = test.find('"')
    needle = test[0:curpos]
    if needle.startswith("http" or "www"):
        needlestack.append(needle)
  else:
    sane = 1
for item in needlestack:
  print item

How can I backup a remote SQL Server database to a local drive?

If you use the Generate Scripts under SSMS, click the Advanced button. Under the 'Generate Scripts for the dependent objects' option, click True. By clicking that any dependencies of each object will also be scripted out in proper order.

MySQL select all rows from last month until (now() - 1 month), for comparative purposes

You can get the first of the month, by calculating the last_day of the month before and add one day. It is awkward, but I think it is better than formatting a date as string and use that for calculation.

select 
  *
from
  yourtable t
where
  /* Greater or equal to the start of last month */
  t.date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) and
  /* Smaller or equal than one month ago */
  t.date <= DATE_SUB(NOW(), INTERVAL 1 MONTH)

Including all the jars in a directory within the Java classpath

All the above solutions work great if you develop and run the Java application outside any IDE like Eclipse or Netbeans.

If you are on Windows 7 and used Eclipse IDE for Development in Java, you might run into issues if using Command Prompt to run the class files built inside Eclipse.

E.g. Your source code in Eclipse is having the following package hierarchy: edu.sjsu.myapp.Main.java

You have json.jar as an external dependency for the Main.java

When you try running Main.java from within Eclipse, it will run without any issues.

But when you try running this using Command Prompt after compiling Main.java in Eclipse, it will shoot some weird errors saying "ClassNotDef Error blah blah".

I assume you are in the working directory of your source code !!

Use the following syntax to run it from command prompt:

  1. javac -cp ".;json.jar" Main.java

  2. java -cp ".;json.jar" edu.sjsu.myapp.Main

    [Don't miss the . above]

This is because you have placed the Main.java inside the package edu.sjsu.myapp and java.exe will look for the exact pattern.

Hope it helps !!

"No backupset selected to be restored" SQL Server 2012

In my case (new sql server install, newly created user) my user simply didn't have the necessary permission. I logged to the Management Studio as sa, then went to Security/Logins, right-click my username, Properties, then in the Server Roles section I checked sysadmin.

php var_dump() vs print_r()

If you're asking when you should use what, I generally use print_r() for displaying values and var_dump() for when having issues with variable types.

What are Keycloak's OAuth2 / OpenID Connect endpoints?

In version 1.9.0 json with all endpoints is at address /auth/realms/{realm}

  • Authorization Endpoint: /auth/realms/{realm}/account
  • Token Endpoint: /auth/realms/{realm}/protocol/openid-connect

Copy existing project with a new name in Android Studio

Perhaps this will help someone.

For Android Studio 4.x Projects, you need following steps:

  • copy project directory to new project directory
  • from Android Studio, open new project directory
  • edit settings.gradle file by updating the rootProject.name='newProjectName'.
  • then sync gradle
  • and here you go the project is ready, and you can start updating manifest, packages, google-services.json and all other stuff

How to give a user only select permission on a database

You could add the user to the Database Level Role db_datareader.

Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.

See Books Online for reference:

http://msdn.microsoft.com/en-us/library/ms189121%28SQL.90%29.aspx

You can add a database user to a database role using the following query:

EXEC sp_addrolemember N'db_datareader', N'userName'

jQuery object equality

First order your object based on key using this function

function sortObject(o) {
    return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}

Then, compare the stringified version of your object, using this funtion

function isEqualObject(a,b){
    return JSON.stringify(sortObject(a)) == JSON.stringify(sortObject(b));
}

Here is an example

Assuming objects keys are ordered differently and are of the same values

var obj1 = {"hello":"hi","world":"earth"}
var obj2 = {"world":"earth","hello":"hi"}

isEqualObject(obj1,obj2);//returns true

pass **kwargs argument to another function with **kwargs

Expanding on @gecco 's answer, the following is an example that'll show you the difference:

def foo(**kwargs):
    for entry in kwargs.items():
        print("Key: {}, value: {}".format(entry[0], entry[1]))

# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})

# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")

Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails

Greyscale Background Css Images

I know it's a really old question, but it's the first result on duckduckgo, so I wanted to share what I think it's a better and more modern solution.

You can use background-blend-mode property to achieve a greyscale image:

#something {
  background-color: #fff;
  background-image: url("yourimage");
  background-blend-mode: luminosity;
}

If you want to remove the effect, just change the blend-mode to initial.

You may need to play a little bit with the background-color if this element is over something with a background. What I've found is that the greyscale does not depend on the actual color but on the alpha value. So, if you have a blue background on the parent, set the same background on #something.

You can also use two images, one with color and the other without and set both as background and play with other blend modes.

https://www.w3schools.com/cssref/pr_background-blend-mode.asp

It won't work on Edge though.

EDIT: I've miss the "fade" part of the question.

If you wan't to make it fade from/to grayscale, you can use a css transition on the background color changeing it's alpha value:

#something {
  background-color: rgba(255,255,255,1);
  background-image: url("yourimage");
  background-blend-mode: luminosity;
  transition: background-color 1s ease-out;
}
#something:hover {
  background-color: rgba(255,255,255,0);
}

I'm also adding a codepen example for completeness https://codepen.io/anon/pen/OBKKVZ

Setting the JVM via the command line on Windows

If you have 2 installations of the JVM. Place the version upfront. Linux : export PATH=/usr/lib/jvm/java-8-oracle/bin:$PATH

This eliminates the ambiguity.

Curl Command to Repeat URL Request

You could use URL sequence substitution with a dummy query string (if you want to use CURL and save a few keystrokes):

curl http://www.myurl.com/?[1-20]

If you have other query strings in your URL, assign the sequence to a throwaway variable:

curl http://www.myurl.com/?myVar=111&fakeVar=[1-20]

Check out the URL section on the man page: https://curl.haxx.se/docs/manpage.html

SQL Server: Is it possible to insert into two tables at the same time?

Before being able to do a multitable insert in Oracle, you could use a trick involving an insert into a view that had an INSTEAD OF trigger defined on it to perform the inserts. Can this be done in SQL Server?

Inserting multiple rows in a single SQL query?

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

Cloning a private Github repo

I have met this issue several times and every time I landed on this page, tried every thing and failed!

It's because I have 2FA enabled!!!

According to https://help.github.com/articles/which-remote-url-should-i-use/#when-2fa-is-enabled

If you have enabled two-factor authentication, or if you are accessing an organization that uses SAML single sign-on, you must provide a personal access token instead of entering your password for HTTPS Git.

  1. Follow this link and create an access token
  2. git clone https://github.com/username/repo_name.git (The default git repo link is good enough!)
  3. Enter your username and use the access token as password!!

Update:

  • If you don't mind exposing your access token in the command line, you can also paste the access token as username then hit enter enter (no need for password).
  • Hate copy&pasting the access token over and over again?
    Use git config credential.helper store (don't do this on machine you don't trust)

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

I've used ng-change:

_x000D_
_x000D_
Date.prototype.addDays = function(days) {_x000D_
  var dat = new Date(this.valueOf());_x000D_
  dat.setDate(dat.getDate() + days);_x000D_
  return dat;_x000D_
}_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
_x000D_
app.controller('DateController', ['$rootScope', '$scope',_x000D_
  function($rootScope, $scope) {_x000D_
    function init() {_x000D_
      $scope.startDate = new Date();_x000D_
      $scope.endDate = $scope.startDate.addDays(14);_x000D_
    }_x000D_
_x000D_
_x000D_
    function load() {_x000D_
      alert($scope.startDate);_x000D_
      alert($scope.endDate);_x000D_
    }_x000D_
_x000D_
    init();_x000D_
    // public methods_x000D_
    $scope.load = load;_x000D_
    $scope.setStart = function(date) {_x000D_
      $scope.startDate = date;_x000D_
    };_x000D_
    $scope.setEnd = function(date) {_x000D_
      $scope.endDate = date;_x000D_
    };_x000D_
_x000D_
  }_x000D_
]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div data-ng-controller="DateController">_x000D_
  <label class="item-input"> <span class="input-label">Start</span>_x000D_
    <input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
  </label>_x000D_
  <label class="item-input"> <span class="input-label">End</span>_x000D_
    <input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
  </label>_x000D_
  <button button="button" ng-disabled="planningForm.$invalid" ng-click="load()" class="button button-positive">_x000D_
    Run_x000D_
  </button>_x000D_
</div <label class="item-input"> <span class="input-label">Start</span>_x000D_
<input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<label class="item-input"> <span class="input-label">End</span>_x000D_
  <input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
</label>
_x000D_
_x000D_
_x000D_

What is a difference between unsigned int and signed int in C?

ISO C states what the differences are.

The int data type is signed and has a minimum range of at least -32767 through 32767 inclusive. The actual values are given in limits.h as INT_MIN and INT_MAX respectively.

An unsigned int has a minimal range of 0 through 65535 inclusive with the actual maximum value being UINT_MAX from that same header file.

Beyond that, the standard does not mandate twos complement notation for encoding the values, that's just one of the possibilities. The three allowed types would have encodings of the following for 5 and -5 (using 16-bit data types):

        two's complement  |  ones' complement   |   sign/magnitude
    +---------------------+---------------------+---------------------+
 5  | 0000 0000 0000 0101 | 0000 0000 0000 0101 | 0000 0000 0000 0101 |
-5  | 1111 1111 1111 1011 | 1111 1111 1111 1010 | 1000 0000 0000 0101 |
    +---------------------+---------------------+---------------------+
  • In two's complement, you get a negative of a number by inverting all bits then adding 1.
  • In ones' complement, you get a negative of a number by inverting all bits.
  • In sign/magnitude, the top bit is the sign so you just invert that to get the negative.

Note that positive values have the same encoding for all representations, only the negative values are different.

Note further that, for unsigned values, you do not need to use one of the bits for a sign. That means you get more range on the positive side (at the cost of no negative encodings, of course).

And no, 5 and -5 cannot have the same encoding regardless of which representation you use. Otherwise, there'd be no way to tell the difference.


As an aside, there are currently moves underway, in both C and C++ standards, to nominate two's complement as the only encoding for negative integers.

How do I set vertical space between list items?

To apply to an entire list, use

ul.space_list li { margin-bottom: 1em; }

Then, in the html:

<ul class=space_list>
<li>A</li>
<li>B</li>
</ul>

maxReceivedMessageSize and maxBufferSize in app.config

The currently accepted answer is incorrect. It is NOT required to set maxBufferSize and maxReceivedMessageSize on the client and the server binding. It depends!

If your request is too large (i.e., method parameters of the service operation are memory intensive) set the properties on the server-side, if the response is too large (i.e., the method return value of the service operation is memory intensive) set the values on the client-side.

For the difference between maxBufferSize and maxReceivedMessageSize see MaxBufferSize property?.

Automatically deleting related rows in Laravel (Eloquent ORM)

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

here's an example:

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

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

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

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

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

Then you can simply call this where you need:

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

DBCC CHECKIDENT Sets Identity to 0

Change statement to

  DBCC CHECKIDENT('TableName', RESEED, 1)

This will start from 2 (or 1 when you recreate table), but it will never be 0.

Group a list of objects by an attribute

Java 8 groupingBy Collector

Probably it's late but I like to share an improved idea to this problem. This is basically the same of @Vitalii Fedorenko's answer but more handly to play around.

You can just use the Collectors.groupingBy() by passing the grouping logic as function parameter and you will get the splitted list with the key parameter mapping. Note that using Optional is used to avoid the unwanted NPE when the provided list is null

public static <E, K> Map<K, List<E>> groupBy(List<E> list, Function<E, K> keyFunction) {
    return Optional.ofNullable(list)
            .orElseGet(ArrayList::new)
            .stream()
            .collect(Collectors.groupingBy(keyFunction));
}

Now you can groupBy anything with this. For the use case here in the question

Map<String, List<Student>> map = groupBy(studlist, Student::getLocation);

Maybe you would like to look into this also Guide to Java 8 groupingBy Collector

The Eclipse executable launcher was unable to locate its companion launcher jar windows

Edit the eclipse.ini file and remove these two lines:

-startup
plugins\org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar 

Creating and throwing new exception

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}

incompatible character encodings: ASCII-8BIT and UTF-8

I had the same problem when parsing CSV files on Ruby 1.9.2 that were correctly parsed on Ruby 1.8. I found the answer here. When opening the CSV file with Ruby CSV module it is necessary to specify UTF-8 enconding as following:

CSV.foreach("file.txt", encoding: "UTF-8") do |row|
   # foo and bar correctly encoded
   foo, bar, ... = row
end

What is a C++ delegate?

Windows Runtime equivalent of a function object in standard C++. One can use the whole function as a parameter (actually that is a function pointer). It is mostly used in conjunction with events. The delegate represents a contract that event handlers much fulfill. It facilitate how a function pointer can work for.

JQuery get data from JSON array

I think you need something like:

var text= data.response.venue.tips.groups[0].items[1].text;

How to use UIVisualEffectView to Blur Image?

Here is how to use UIVibrancyEffect and UIBlurEffect with UIVisualEffectView

Objective-C:

// Blur effect
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
[blurEffectView setFrame:self.view.bounds];
[self.view addSubview:blurEffectView];

// Vibrancy effect
UIVibrancyEffect *vibrancyEffect = [UIVibrancyEffect effectForBlurEffect:blurEffect];
UIVisualEffectView *vibrancyEffectView = [[UIVisualEffectView alloc] initWithEffect:vibrancyEffect];
[vibrancyEffectView setFrame:self.view.bounds];

// Label for vibrant text
UILabel *vibrantLabel = [[UILabel alloc] init];
[vibrantLabel setText:@"Vibrant"];
[vibrantLabel setFont:[UIFont systemFontOfSize:72.0f]];
[vibrantLabel sizeToFit];
[vibrantLabel setCenter: self.view.center];

// Add label to the vibrancy view
[[vibrancyEffectView contentView] addSubview:vibrantLabel];

// Add the vibrancy view to the blur view
[[blurEffectView contentView] addSubview:vibrancyEffectView];

Swift 4:

    // Blur Effect
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = view.bounds
    view.addSubview(blurEffectView)

    // Vibrancy Effect
    let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
    let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
    vibrancyEffectView.frame = view.bounds

    // Label for vibrant text
    let vibrantLabel = UILabel()
    vibrantLabel.text = "Vibrant"
    vibrantLabel.font = UIFont.systemFont(ofSize: 72.0)
    vibrantLabel.sizeToFit()
    vibrantLabel.center = view.center

    // Add label to the vibrancy view
    vibrancyEffectView.contentView.addSubview(vibrantLabel)

    // Add the vibrancy view to the blur view
    blurEffectView.contentView.addSubview(vibrancyEffectView)

What is an undefined reference/unresolved external symbol error and how do I fix it?

Declared but did not define a variable or function.

A typical variable declaration is

extern int x;

As this is only a declaration, a single definition is needed. A corresponding definition would be:

int x;

For example, the following would generate an error:

extern int x;
int main()
{
    x = 0;
}
//int x; // uncomment this line for successful definition

Similar remarks apply to functions. Declaring a function without defining it leads to the error:

void foo(); // declaration only
int main()
{
   foo();
}
//void foo() {} //uncomment this line for successful definition

Be careful that the function you implement exactly matches the one you declared. For example, you may have mismatched cv-qualifiers:

void foo(int& x);
int main()
{
   int x;
   foo(x);
}
void foo(const int& x) {} //different function, doesn't provide a definition
                          //for void foo(int& x)
                          

Other examples of mismatches include

  • Function/variable declared in one namespace, defined in another.
  • Function/variable declared as class member, defined as global (or vice versa).
  • Function return type, parameter number and types, and calling convention do not all exactly agree.

The error message from the compiler will often give you the full declaration of the variable or function that was declared but never defined. Compare it closely to the definition you provided. Make sure every detail matches.

Is putting a div inside an anchor ever correct?

If you want to avoid the semantic trouble of placing divs inside anchor tags, just place the anchor tag on the same level as the divs, wrap them all with a container with position: relative, make your anchor tag position: absolute and expand it to fill the container. Also if it's not on the end of the content flow make sure you throw a z-index in there to place it above the content.

As suggested I have added a markup code:

<div class="div__container>
  <div class="div__one>
  </div>
  <div class="div__two">
  </div>
  <a href="#"></a>
</div>

And the css:

.div__container {
  position: relative; 
}
.div__container a {
  position: absolute;
  top: 0;
  bottom: 0;      
  left: 0;
  right: 0;
  z-index: 999;
}

How to get a reversed list view on a list in Java?

java.util.Deque has descendingIterator() - if your List is a Deque, you can use that.

How can I escape white space in a bash loop list?

I use

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in $( find "$1" -type d ! -path "$1" )
do
  echo $f
done
IFS=$SAVEIFS

Wouldn't that be enough?
Idea taken from http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html

http://localhost/ not working on Windows 7. What's the problem?

Have you try the iis? Go to Control Panel->Programs and Features->Turn Windows features on or off (side bar). Try installing or reinstalling the Internet Information Service. I've a windows 7 with iis, with .net and php, and it works great...

Pure CSS to make font-size responsive based on dynamic amount of characters

This solution might also help :

$(document).ready(function () {
    $(window).resize(function() {
        if ($(window).width() < 600) {
            $('body').css('font-size', '2.8vw' );
        } else if ($(window).width() >= 600 && $(window).width() < 750) {
            $('body').css('font-size', '2.4vw');
        } 
         // and so on... (according to our needs)
        } else if ($(window).width() >= 1200) {
            $('body').css('font-size', '1.2vw');
        }
    }); 
  });

It worked for me well !

Disable Proximity Sensor during call

I also had problem with proximity sensor (I shattered screen in that region on my Nexus 6, Android Marshmallow) and none of proposed solutions / third party apps worked when I tried to disable proximity sensor. What worked for me was to calibrate the sensor using Proximity Sensor Reset/Repair. You have to follow the instruction in app (cover sensor and uncover it) and then restart your phone. Although my sensor is no longer behind the glass, it still showed slightly different results when covered / uncovered and recalibration did the job.

What I tried and didn't work? Proximity Screen Off Lite, Macrodroid and KinScreen.

What would've I tried had it still not worked?[XPOSED] Sensor Disabler, but it requires you to be rooted and have Xposed Framework, so I'm really glad I've found the easier way.

android TextView: setting the background color dynamically doesn't work

To set red color:

textView.setBackgroundColor(0xfff00000);

Or

<color name="solid_red">#fff00000</color>

textView.setBackgroundResource(R.color.solid_red);

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

This issue could be because adb incompatibility with the newest version of the platform SDK.

Try the following:

  1. If you are using Genymotion, manually set the Android SDK within Genymotion settings to your sdk path. Go to Genymotion -> settings -> ADB -> Use custom SDK Tools -> Browse and ender your local SDK path.

  2. If you haverecently updated your platform-tools plugin version, revert back to 23.0.1.

Its a bug within ADB, one of the above must most likely be your solution.

Count unique values in a column in Excel

Count unique with a condition. Col A is ID and using condition ID=32, Col B is Name and we are trying to count the unique names for a particular ID

=SUMPRODUCT((B2:B12<>"")*(A2:A12=32)/COUNTIF(B2:B12,B2:B12))

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

For me changing the Jenkins version helped.

  <parent>
    <groupId>org.jenkins-ci.plugins</groupId>
    <artifactId>plugin</artifactId>
    <version>1.642.4</version><!-- which version of Jenkins is this plugin built against? -->
  </parent>

Java - Create a new String instance with specified length and filled with specific character. Best solution?

Solution using Google Guava, since I prefer it to Apache Commons-Lang:

/**
 * Returns a String with exactly the given length composed entirely of
 * the given character.
 * @param length the length of the returned string
 * @param c the character to fill the String with
 */
public static String stringOfLength(final int length, final char c)
{
    return Strings.padEnd("", length, c);
}

GitHub: invalid username or password

I have got the success using the following commands.

git config --unset-all credential.helper
git config --global --unset-all credential.helper
git config --system --unset-all credential.helper

Try and let me know if these are working for you.

How can I get the error message for the mail() function?

As the others have said, there is no error tracking for send mail it return the boolean result of adding the mail to the outgoing queue. If you want to track true success failure try using SMTP with a mail library like Swift Mailer, Zend_Mail, or phpmailer.

How to use MySQL DECIMAL?

Although the answers above seems correct, just a simple explanation to give you an idea of how it works.

Suppose that your column is set to be DECIMAL(13,4). This means that the column will have a total size of 13 digits where 4 of these will be used for precision representation.

So, in summary, for that column you would have a max value of: 999999999.9999

Read file line by line using ifstream in C++

This answer is for visual studio 2017 and if you want to read from text file which location is relative to your compiled console application.

first put your textfile (test.txt in this case) into your solution folder. After compiling keep text file in same folder with applicationName.exe

C:\Users\"username"\source\repos\"solutionName"\"solutionName"

#include <iostream>
#include <fstream>

using namespace std;
int main()
{
    ifstream inFile;
    // open the file stream
    inFile.open(".\\test.txt");
    // check if opening a file failed
    if (inFile.fail()) {
        cerr << "Error opeing a file" << endl;
        inFile.close();
        exit(1);
    }
    string line;
    while (getline(inFile, line))
    {
        cout << line << endl;
    }
    // close the file stream
    inFile.close();
}

What does "publicPath" in Webpack do?

You can use publicPath to point to the location where you want webpack-dev-server to serve its "virtual" files. The publicPath option will be the same location of the content-build option for webpack-dev-server. webpack-dev-server creates virtual files that it will use when you start it. These virtual files resemble the actual bundled files webpack creates. Basically you will want the --content-base option to point to the directory your index.html is in. Here is an example setup:

//application directory structure
/app/
/build/
/build/index.html
/webpack.config.js


//webpack.config.js
var path = require("path");
module.exports = {
...
  output: {
    path: path.resolve(__dirname, "build"),
    publicPath: "/assets/",
    filename: "bundle.js"
  }
};  


//index.html
<!DOCTYPE>
<html>
...
<script src="assets/bundle.js"></script>
</html>

//starting a webpack-dev-server from the command line
$ webpack-dev-server --content-base build 

webpack-dev-server has created a virtual assets folder along with a virtual bundle.js file that it refers to. You can test this by going to localhost:8080/assets/bundle.js then check in your application for these files. They are only generated when you run the webpack-dev-server.

Number of days between two dates in Joda-Time

The accepted answer builds two LocalDate objects, which are quite expensive if you are reading lot of data. I use this:

  public static int getDaysBetween(DateTime earlier, DateTime later)
  {
    return (int) TimeUnit.MILLISECONDS.toDays(later.getMillis()- earlier.getMillis());
  }

By calling getMillis() you use already existing variables.
MILLISECONDS.toDays() then, uses a simple arithmetic calculation, does not create any object.

How do you convert epoch time in C#?

In case you need to convert a timeval struct (seconds, microseconds) containing UNIX time to DateTime without losing precision, this is how:

DateTime _epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private DateTime UnixTimeToDateTime(Timeval unixTime)
{
    return _epochTime.AddTicks(
        unixTime.Seconds * TimeSpan.TicksPerSecond +
        unixTime.Microseconds * TimeSpan.TicksPerMillisecond/1000);
}

How to fix: Error device not found with ADB.exe

I had this problem suddenly crop up in Windows 7 with my Nexus One - somehow the USB drivers had been uninstalled. I ran android-sdk/SDK Manager.exe, checked Extras/Google USB Driver and installed it. Then I unplugged the phone and plugged it back in, and ran "adb devices" to confirm the phone was attached.

This doesn't work for all phones, just the ones listed here: http://developer.android.com/sdk/win-usb.html

How to POST JSON data with Python Requests?

Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call:

>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
 'data': '{"key": "value"}',
 'files': {},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Content-Length': '16',
             'Content-Type': 'application/json',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
             'X-Request-Id': 'xx-xx-xx'},
 'json': {'key': 'value'},
 'origin': 'x.x.x.x',
 'url': 'http://httpbin.org/post'}

How to use "not" in xpath?

you can use not(expression) function

or

expression != true()

The difference between Classes, Objects, and Instances

Class is Data Type,You use this type to create object.

  • Instance is Logical but object is Physical means occupies some memory.

  • We can create an instance for abstract class as well as for interface, but we cannot create an
    object for those.

  • Object is instance of class and instance means representative of class i.e object.

  • Instance refers to Reference of an object.

  • Object is actually pointing to memory address of that instance.

  • You can’t pass instance over the layers but you can pass the object over the layers

  • You can’t store an instance but you can store an object

  • A single object can have more than one instance.

  • Instance will have the both class definition and the object definition where as in object it will have only the object definition.

Syntax of Object:

 Classname var=new Classname();

But for instance creation it returns only a pointer refering to an object, syntax is :

 Classname varname;

How do I find out if first character of a string is a number?

I just came across this question and thought on contributing with a solution that does not use regex.

In my case I use a helper method:

public boolean notNumber(String input){
    boolean notNumber = false;
    try {
        // must not start with a number
        @SuppressWarnings("unused")
        double checker = Double.valueOf(input.substring(0,1));
    }
    catch (Exception e) {
        notNumber = true;           
    }
    return notNumber;
}

Probably an overkill, but I try to avoid regex whenever I can.

Maintaining Session through Angular.js

Here is a kind of snippet for you:

app.factory('Session', function($http) {
  var Session = {
    data: {},
    saveSession: function() { /* save session data to db */ },
    updateSession: function() { 
      /* load data from db */
      $http.get('session.json').then(function(r) { return Session.data = r.data;});
    }
  };
  Session.updateSession();
  return Session; 
});

Here is Plunker example how you can use that: http://plnkr.co/edit/Fg3uF4ukl5p88Z0AeQqU?p=preview

How to set my phpmyadmin user session to not time out so quickly?

To increase the phpMyAdmin Session Timeout, open config.inc.php in the root phpMyAdmin directory and add this setting (anywhere).

$cfg['LoginCookieValidity'] = <your_new_timeout>;

Where <your_new_timeout> is some number larger than 1800.

Note:

Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.

C# create simple xml file

I'd recommend serialization,

public class Person
{
      public  string FirstName;
      public  string MI;
      public  string LastName;
}

static void Serialize()
{
      clsPerson p = new Person();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(System.Console.Out, p);
      System.Console.WriteLine();
      System.Console.WriteLine(" --- Press any key to continue --- ");
      System.Console.ReadKey();
}

You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:

using System;
using System.Xml;

public class GenerateXml {
    private static void Main() {
        XmlDocument doc = new XmlDocument();
        XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
        doc.AppendChild(docNode);

        XmlNode productsNode = doc.CreateElement("products");
        doc.AppendChild(productsNode);

        XmlNode productNode = doc.CreateElement("product");
        XmlAttribute productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "01";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);

        XmlNode nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("Java"));
        productNode.AppendChild(nameNode);
        XmlNode priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        // Create and add another product node.
        productNode = doc.CreateElement("product");
        productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "02";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);
        nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("C#"));
        productNode.AppendChild(nameNode);
        priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        doc.Save(Console.Out);
    }
}

And if it needs to be fast, use XmlWriter:

public static void WriteXML()
{
    // Create an XmlWriterSettings object with the correct options.
    System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
    settings.Indent = true;
    settings.IndentChars = "    "; //  "\t";
    settings.OmitXmlDeclaration = false;
    settings.Encoding = System.Text.Encoding.UTF8;

    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))
    {

        writer.WriteStartDocument();
        writer.WriteStartElement("books");

        for (int i = 0; i < 100; ++i)
        {
            writer.WriteStartElement("book");
            writer.WriteElementString("item", "Book "+ (i+1).ToString());
            writer.WriteEndElement();
        }

        writer.WriteEndElement();

        writer.Flush();
        writer.Close();
    } // End Using writer 

}

And btw, the fastest way to read XML is XmlReader:

public static void ReadXML()
{
    using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"))
    {
        while (xmlReader.Read())
        {
            if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
            {
                if (xmlReader.HasAttributes)
                    System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
            }

        } // Whend 

    } // End Using xmlReader

    System.Console.ReadKey();
}

And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:
https://xmltocsharp.azurewebsites.net/

Hide Text with CSS, Best Practice?

Can't you use simply display: none; like this

HTML

<div id="web-title">
   <a href="http://website.com" title="Website" rel="home">
       <span class="webname">Website Name</span>
   </a>
</div>

CSS

.webname {
   display: none;
}

Or how about playing with visibility if you are concerned to reserve the space

.webname {
   visibility: hidden;
}

How can I check whether a numpy array is empty or not?

http://www.scipy.org/Tentative_NumPy_Tutorial#head-6a1bc005bd80e1b19f812e1e64e0d25d50f99fe2

NumPy's main object is the homogeneous multidimensional array. In Numpy dimensions are called axes. The number of axes is rank. Numpy's array class is called ndarray. It is also known by the alias array. The more important attributes of an ndarray object are:

ndarray.ndim
the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.

ndarray.shape
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.

ndarray.size
the total number of elements of the array. This is equal to the product of the elements of shape.

NGinx Default public www location?

In my case it was in /usr/share/nginx/html

you can try to find by performing a search

find / -name html

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.

Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.

The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.

It does look like the checkout --orphan is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init a repo, set up a remote tracking branch (you do want the one branch only?), and then fetch that single branch, which feels long winded with more opportunity for mistakes.

Edit: For the 'clone' step see this answer

Match two strings in one line with grep

I often run into the same problem as yours, and I just wrote a piece of script:

function m() { # m means 'multi pattern grep'

    function _usage() {
    echo "usage: COMMAND [-inH] -p<pattern1> -p<pattern2> <filename>"
    echo "-i : ignore case"
    echo "-n : show line number"
    echo "-H : show filename"
    echo "-h : show header"
    echo "-p : specify pattern"
    }

    declare -a patterns
    # it is important to declare OPTIND as local
    local ignorecase_flag  filename linum header_flag colon result OPTIND

    while getopts "iHhnp:" opt; do
    case $opt in
        i)
        ignorecase_flag=true ;;
        H)
        filename="FILENAME," ;;
        n)
        linum="NR," ;;
        p)
        patterns+=( "$OPTARG" ) ;;
        h)
        header_flag=true ;;
        \?)
        _usage
        return ;;
    esac
    done

    if [[ -n $filename || -n $linum ]]; then
    colon="\":\","
    fi

    shift $(( $OPTIND - 1 ))

    if [[ $ignorecase_flag == true ]]; then
    for s in "${patterns[@]}"; do
            result+=" && s~/${s,,}/"
    done
    result=${result# && }
    result="{s=tolower(\$0)} $result"
    else
    for s in "${patterns[@]}"; do
            result="$result && /$s/"
    done
    result=${result# && }
    fi

    result+=" { print "$filename$linum$colon"\$0 }"

    if [[ ! -t 0 ]]; then       # pipe case
    cat - | awk "${result}"
    else
    for f in "$@"; do
        [[ $header_flag == true ]] && echo "########## $f ##########"
        awk "${result}" $f
    done
    fi
}

Usage:

echo "a b c" | m -p A 
echo "a b c" | m -i -p A # a b c

You can put it in .bashrc if you like.

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

This suggestion is based on pixel manipulation in canvas 2d context.

From MDN:

You can directly manipulate pixel data in canvases at the byte level

To manipulate pixels we'll use two functions here - getImageData and putImageData.

getImageData usage:

var myImageData = context.getImageData(left, top, width, height);

The putImageData syntax:

context.putImageData(myImageData, x, y); 

Where context is your canvas 2d context, and x and y are the position on the canvas.

So to get red green blue and alpha values, we'll do the following:

var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];

Where x is the horizontal offset, y is the vertical offset.

The code making image half-transparent:

var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var img = new Image();
img.onload  = function() {
   c.drawImage(img, 0, 0);
   var ImageData = c.getImageData(0,0,img.width,img.height);
   for(var i=0;i<img.height;i++)
      for(var j=0;j<img.width;j++)
         ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255]
   c.putImageData(ImageData,0,0);//put image data back
}
img.src = 'image.jpg';

You can make you own "shaders" - see full MDN article here

Bound method error

For this thing you can use @property as an decorator, so you could use instance methods as attributes. For example:

class Word_Parser:
    def __init__(self, sentences):
        self.sentences = sentences

    @property
    def parser(self):
        self.word_list = self.sentences.split()

    @property
    def sort_word_list(self):
        self.sorted_word_list = self.word_list.sort()

    @property
    def num_words(self):
        self.num_words = len(self.word_list)

test = Word_Parser("mary had a little lamb")
test.parser()
test.sort_word_list()
test.num_words()
print test.word_list
print test.sort_word_list
print test.num_words

so you can use access the attributes without calling (i.e., without the ()).

To switch from vertical split to horizontal split fast in Vim

Ctrl-w followed by H, J, K or L (capital) will move the current window to the far left, bottom, top or right respectively like normal cursor navigation.

The lower case equivalents move focus instead of moving the window.

How to split large text file in windows?

You can use the command split for this task. For example this command entered into the command prompt

split YourLogFile.txt -b 500m

creates several files with a size of 500 MByte each. This will take several minutes for a file of your size. You can rename the output files (by default called "xaa", "xab",... and so on) to *.txt to open it in the editor of your choice.

Make sure to check the help file for the command. You can also split the log file by number of lines or change the name of your output files.

(tested on Windows 7 64 bit)

Serial Port (RS -232) Connection in C++

For the answer above, the default serial port is

        serialParams.BaudRate = 9600;
        serialParams.ByteSize = 8;
        serialParams.StopBits = TWOSTOPBITS;
        serialParams.Parity = NOPARITY;

How to check version of python modules?

I myself work in a heavily restricted server environment and unfortunately none of the solutions here are working for me. There may be no glove solution that fits all, but I figured out a swift workaround by reading the terminal output of pip freeze within my script and storing the modules labels and versions in a dictionary.

import os
os.system('pip freeze > tmpoutput')
with open('tmpoutput', 'r') as f:
    modules_version = f.read()
  
module_dict = {item.split("==")[0]:item.split("==")[-1] for item in modules_versions.split("\n")}

Retrieve your module's versions through passing the module label key, e.g.:

>>  module_dict["seaborn"]
'0.9.0'

How to give the background-image path in CSS?

Use the below.

background-image: url("././images/image.png");

This shall work.

Does "\d" in regex mean a digit?

This is just a guess, but I think your editor actually matches every single digit — 1 2 3 — but only odd matches are highlighted, to distinguish it from the case when the whole 123 string is matched.

Most regex consoles highlight contiguous matches with different colors, but due to the plugin settings, terminal limitations or for some other reason, only every other group might be highlighted in your case.

how do I strip white space when grabbing text with jQuery?

Javascript has built in trim:

str.trim()

It doesn't work in IE8. If you have to support older browsers, use Tuxmentat's or Paul's answer.

Android: keep Service running when app is killed

In your service, add the following code.

@Override
public void onTaskRemoved(Intent rootIntent){
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
    AlarmManager.ELAPSED_REALTIME,
    SystemClock.elapsedRealtime() + 1000,
    restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
 }

Date validation with ASP.NET validator

Best option would be

Add a compare validator to the web form. Set its controlToValidate. Set its Type property to Date. Set its operator property to DataTypeCheck eg:

<asp:CompareValidator
    id="dateValidator" runat="server" 
    Type="Date"
    Operator="DataTypeCheck"
    ControlToValidate="txtDatecompleted" 
    ErrorMessage="Please enter a valid date.">
</asp:CompareValidator>

How do I disable a Pylint warning?

Python syntax does permit more than one statement on a line, separated by semicolon (;). However, limiting each line to one statement makes it easier for a human to follow a program's logic when reading through it.

So, another way of solving this issue, is to understand why the lint message is there and not put more than one statement on a line.

Yes, you may find it easier to write multiple statements per line, however, Pylint is for every other reader of your code not just you.

How exactly does the android:onClick XML attribute differ from setOnClickListener?

To make your life easier and avoid the Anonymous Class in setOnClicklistener (), implement a View.OnClicklistener Interface as below:

public class YourClass extends CommonActivity implements View.OnClickListener, ...

this avoids:

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        yourMethod(v);
    }
});

and goes directly to:

@Override
public void onClick(View v) {
  switch (v.getId()) {
    case R.id.your_view:
      yourMethod();
      break;
  }
}

eval command in Bash and its typical uses

Simply think of eval as "evaluating your expression one additional time before execution"

eval echo \${$n} becomes echo $1 after the first round of evaluation. Three changes to notice:

  • The \$ became $ (The backslash is needed, otherwise it tries to evaluate ${$n}, which means a variable named {$n}, which is not allowed)
  • $n was evaluated to 1
  • The eval disappeared

In the second round, it is basically echo $1 which can be directly executed.

So eval <some command> will first evaluate <some command> (by evaluate here I mean substitute variables, replace escaped characters with the correct ones etc.), and then run the resultant expression once again.

eval is used when you want to dynamically create variables, or to read outputs from programs specifically designed to be read like this. See http://mywiki.wooledge.org/BashFAQ/048 for examples. The link also contains some typical ways in which eval is used, and the risks associated with it.

Github Push Error: RPC failed; result=22, HTTP code = 413

I had this error (error: RPC failed; result=22, HTTP code = 413) when I tried to push my initial commit to a new BitBucket repository. The error occurred for me because the BitBucket repo had no master branch. If you are using SourceTree you can create a master branch on the origin by pressing the Git Flow button.

Javascript (+) sign concatenates instead of giving sum of variables

Joachim Sauer's answer will work in scenarios like this. But there are some instances where adding parentheses won’t help.

For example: You are passing “sum of value of an input element and an integer” as an argument to a function.

arg1 = $("#elemId").val();   // value is treated as string
arg2 = 1;
someFuntion(arg1 + arg2);    // and so the values are merged here
someFuntion((arg1 + arg2));  // and here

You can make it work by using Number()

arg1 = Number($("#elemId").val());
arg2 = 1;
someFuntion(arg1 + arg2);

or

arg1 = $("#elemId").val();
arg2 = 1;
someFuntion(Number(arg1) + arg2);

Change Twitter Bootstrap Tooltip content on click

For BS4 (and BS3 with minor changes) .. after hours of searching and trials, i came up with the most reliable solution for this problem and it even solves the problem of opening more than one (tooltip or popover) at the same time, and the problem of opening automatically after losing focus, etc.

_x000D_
_x000D_
$('[data-toggle="tooltip"]').tooltip({_x000D_
  trigger: 'hover'_x000D_
}).on('shown.bs.tooltip', function() {_x000D_
  var link = $(this);_x000D_
  var data = '';_x000D_
  data += '<ul style="list-style-type:none;margin:0;padding:0;text-align:left;font-size:12px">';_x000D_
  data += ' <li>Sherif Salah</li>';_x000D_
  data += ' <li>Muhammad Salah</li>';_x000D_
  data += ' <li>and a gazillion more...</li>';_x000D_
  data += '</ul>';_x000D_
  link.attr('data-original-title', data);_x000D_
  setTimeout(function() {_x000D_
    if (link.is(':hover')) {_x000D_
      link.tooltip("dispose").tooltip("show");_x000D_
    }_x000D_
  }, 1000);_x000D_
});
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">_x000D_
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="card">_x000D_
    <div class="card-body text-center">_x000D_
      <a href="JavaScript:void(0);" class="btn btn-sm btn-link" data-toggle="tooltip" data-placement="top" data-html="true" title="Loading...">gazillion</a>_x000D_
    </div>_x000D_
  </div>_x000D_
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

Update Model from Database doesn't works for me.

I had to remove the conflicted entity, then execute Update Model from Database, lastly rebuild the solution. After that, everything works fine.

How to delete a row from GridView?

hi how to delete from datagridview

1.make query delete by id
2.type

tabletableadaptor.delete
query(datagridwiewX1.selectedrows[0].cell[0].value.tostring);

Using <style> tags in the <body> with other HTML

When I see that the big-site Content Management Systems routinely put some <style> elements (some, not all) close to the content that relies on those classes, I conclude that the horse is out of the barn.

Go look at page sources from cnn.com, nytimes.com, huffingtonpost.com, your nearest big-city newspaper, etc. All of them do this.

If there's a good reason to put an extra <style> section somewhere in the body -- for instance if you're include()ing diverse and independent page elements in real time and each has an embedded <style> of its own, and the organization will be cleaner, more modular, more understandable, and more maintainable -- I say just bite the bullet. Sure it would be better if we could have "local" style with restricted scope, like local variables, but you go to work with the HTML you have, not the HTML you might want or wish to have at a later time.

Of course there are potential drawbacks and good (if not always compelling) reasons to follow the orthodoxy, as others have elaborated. But to me it looks more and more like thoughtful use of <style> in <body> has already gone mainstream.

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

ListenForClients is getting invoked twice (on two different threads) - once from the constructor, once from the explicit method call in Main. When two instances of the TcpListener try to listen on the same port, you get that error.

Get top first record from duplicate records having no unique identity

YOur best bet is to fix the datbase design and add the identioty column to the table. Why do you havea table without one in the first place? Especially one with duplicate records! Clearly the database itself needs redesigning.

And why do you have to have this in a view, why isn't your solution with the temp table a valid solution? Views are not usually a really good thing to do to a perfectly nice database.

Oracle SQL - select within a select (on the same table!)

SELECT eh."Gc_Staff_Number",
       eh."Start_Date",
       MAX(eh2."End_Date") AS "End_Date"
FROM   "Employment_History" eh
LEFT JOIN  "Employment_History" eh2
ON eh."Employee_Number" = eh2."Employee_Number" and eh2."Current_Flag" != 'Y'
WHERE  eh."Current_Flag" = 'Y' 
GROUP BY eh."Gc_Staff_Number",
       eh."Start_Date

Disable firefox same origin policy

I wrote an add-on to overcome this issue in Firefox (Chrome, Opera version will have soon). It works with the latest Firefox version, with beautiful UI and support JS regex: https://addons.mozilla.org/en-US/firefox/addon/cross-domain-cors

enter image description here

PHP check whether property exists in object or class

Using array_key_exists() on objects is Deprecated in php 7.4

Instead either isset() or property_exists() should be used

reference : php.net

Entity Framework - Linq query with order by and group by

You can try to cast the result of GroupBy and Take into an Enumerable first then process the rest (building on the solution provided by NinjaNye

var groupByReference = (from m in context.Measurements
                              .GroupBy(m => m.Reference)
                              .Take(numOfEntries).AsEnumerable()
                               .Select(g => new {Creation = g.FirstOrDefault().CreationTime, 
                                             Avg = g.Average(m => m.CreationTime.Ticks),
                                                Items = g })
                              .OrderBy(x => x.Creation)
                              .ThenBy(x => x.Avg)
                              .ToList() select m);

Your sql query would look similar (depending on your input) this

SELECT TOP (3) [t1].[Reference] AS [Key]
FROM (
    SELECT [t0].[Reference]
    FROM [Measurements] AS [t0]
    GROUP BY [t0].[Reference]
    ) AS [t1]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref1'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref2'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]

How do I add a .click() event to an image?

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script> 
<script type="text/javascript" src="jquery-2.1.0.js"></script> 
<script type="text/javascript" >
function openOnImageClick()
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
 var img = document.createElement('img');
 img.setAttribute('src', 'tiger.jpg');
  img.setAttribute('width', '200');
   img.setAttribute('height', '150');
  document.getElementById("images").appendChild(img);


}


</script>
</head>
<body>

<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>

<div id="images" >
</div>

<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
<img src="Logo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />

</body>
</html> 

Adding files to a GitHub repository

You can use Git GUI on Windows, see instructions:

  1. Open the Git Gui (After installing the Git on your computer).

enter image description here

  1. Clone your repository to your local hard drive:

enter image description here

  1. After cloning, GUI opens, choose: "Rescan" for changes that you made:

enter image description here

  1. You will notice the scanned files:

enter image description here

  1. Click on "Stage Changed":

enter image description here

  1. Approve and click "Commit":

enter image description here

  1. Click on "Push":

enter image description here

  1. Click on "Push":

enter image description here

  1. Wait for the files to upload to git:

enter image description here

enter image description here

Creating a textarea with auto-resize

Found an one liner from here;

<textarea name="text" oninput="this.style.height = ''; this.style.height = this.scrollHeight +'px'"></textarea>

How to get a thread and heap dump of a Java process on Windows that's not running in a console

If you are using JDK 1.6 or above, You can use jmap command to take a heap Dump of a Java process, condition is you should known ProcessID.

If you are on Windows Machine, you can use Task Manager to get PID. For Linux machine you can use varieties of command like ps -A | grep java or netstat -tupln | grep java or top | grep java, depends on your application.

Then you can use the command like jmap -dump:format=b,file=sample_heap_dump.hprof 1234 where 1234 is PID.

There are varieties of tool available to interpret the hprof file. I will recommend Oracle's visualvm tool, which is simple to use.

Checking for empty result (php, pdo, mysql)

One more approach to consider:

When I build an HTML table or other database-dependent content (usually via an AJAX call), I like to check if the SELECT query returned any data before working on any markup. If there is no data, I simply return "No data found..." or something to that effect. If there is data, then go forward, build the headers and loop through the content, etc. Even though I will likely limit my database to MySQL, I prefer to write portable code, so rowCount() is out. Instead, check the the column count. A query that returns no rows also returns no columns.

$stmt->execute();
$cols = $stmt->columnCount(); // no columns == no result set
if ($cols > 0) {
    // non-repetitive markup code here
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

How to disable the resize grabber of <textarea>?

<textarea style="resize:none" name="name" cols="num" rows="num"></textarea>

Just an example

How to pass a parameter like title, summary and image in a Facebook sharer URL

On the Developers bugs Facebook site, the last answer about that (parameters with sharer.php), makes me believe it was a bug that was going to be resolved. Am I right?

https://developers.facebook.com/x/bugs/357750474364812/

Ibrahim Faour · · Facebook Platform Team

Apologies for the inconvenience. We aim to update our external reports as soon as we get a resolution on issues. I do understand that sometimes the answer provided may not be satisfying, but we are eager to keep our platform as stable and efficient as possible. Thanks!

Are HTTPS URLs encrypted?

Linking to my answer on a duplicate question. Not only is the URL available in the browsers history, the server side logs but it's also sent as the HTTP Referer header which if you use third party content, exposes the URL to sources outside your control.

How do I tell matplotlib that I am done with a plot?

There is a clear figure command, and it should do it for you:

plt.clf()

If you have multiple subplots in the same figure

plt.cla()

clears the current axes.

Parse HTML in Android

We all know that programming have endless possibilities.There are numbers of solutions available for a single problem so i think all of the above solutions are perfect and may be helpful for someone but for me this one save my day..

So Code goes like this

  private void getWebsite() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        final StringBuilder builder = new StringBuilder();

        try {
          Document doc = Jsoup.connect("http://www.ssaurel.com/blog").get();
          String title = doc.title();
          Elements links = doc.select("a[href]");

          builder.append(title).append("\n");

          for (Element link : links) {
            builder.append("\n").append("Link : ").append(link.attr("href"))
            .append("\n").append("Text : ").append(link.text());
          }
        } catch (IOException e) {
          builder.append("Error : ").append(e.getMessage()).append("\n");
        }

        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            result.setText(builder.toString());
          }
        });
      }
    }).start();
  }

You just have to call the above function in onCreate Method of your MainActivity

I hope this one is also helpful for you guys.

Also read the original blog at Medium

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

How to hide column of DataGridView when using custom DataSource?

I"m not sure if its too late, but the problem is that, you cannot set the columns in design mode if you are binding at runtime. So if you are binding at runtime, go ahead and remove the columns from the design mode and do it pragmatically

ex..

     if (dt.Rows.Count > 0)
    {
        dataGridViewProjects.DataSource = dt;
        dataGridViewProjects.Columns["Title"].Width = 300;
        dataGridViewProjects.Columns["ID"].Visible = false;
    }

Get value of c# dynamic property via string

Similar to the accepted answer, you can also try GetField instead of GetProperty.

d.GetType().GetField("value2").GetValue(d);

Depending on how the actual Type was implemented, this may work when GetProperty() doesn't and can even be faster.

What is the apply function in Scala?

It comes from the idea that you often want to apply something to an object. The more accurate example is the one of factories. When you have a factory, you want to apply parameter to it to create an object.

Scala guys thought that, as it occurs in many situation, it could be nice to have a shortcut to call apply. Thus when you give parameters directly to an object, it's desugared as if you pass these parameters to the apply function of that object:

class MyAdder(x: Int) {
  def apply(y: Int) = x + y
}

val adder = new MyAdder(2)
val result = adder(4) // equivalent to x.apply(4)

It's often use in companion object, to provide a nice factory method for a class or a trait, here is an example:

trait A {
  val x: Int
  def myComplexStrategy: Int
}

object A {
  def apply(x: Int): A = new MyA(x)

  private class MyA(val x: Int) extends A {
    val myComplexStrategy = 42
  }
}

From the scala standard library, you might look at how scala.collection.Seq is implemented: Seq is a trait, thus new Seq(1, 2) won't compile but thanks to companion object and apply, you can call Seq(1, 2) and the implementation is chosen by the companion object.

Full-screen iframe with a height of 100%

As per https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe, percentage values are no longer allowed. But the following worked for me

<iframe width="100%" height="this.height=window.innerHeight;" style="border:none" src=""></iframe>

Though width:100% works, height:100% does not work. So window.innerHeight has been used. You can also use css pixels for height.

Working code: Link Working site: Link

How can I alter a primary key constraint using SQL syntax?

you can rename constraint objects using sp_rename (as described in this answer)

for example:

EXEC sp_rename N'schema.MyIOldConstraint', N'MyNewConstraint'

select dept names who have more than 2 employees whose salary is greater than 1000

SELECT DEPTNAME
FROM(SELECT D.DEPTNAME,COUNT(EMPID) AS TOTEMP
     FROM DEPT AS D,EMPLOYEE AS E
     WHERE D.DEPTID=E.DEPTID AND SALARY>1000
     GROUP BY D.DEPTID
     )
WHERE TOTEMP>2;

Is there a way to 'uniq' by column?

To consider multiple column.

Sort and give unique list based on column 1 and column 3:

sort -u -t : -k 1,1 -k 3,3 test.txt
  • -t : colon is separator
  • -k 1,1 -k 3,3 based on column 1 and column 3

iOS: UIButton resize according to text length

If you want to resize the text as opposed to the button, you can use ...

button.titleLabel.adjustsFontSizeToFitWidth = YES;
button.titleLabel.minimumScaleFactor = .5;
// The .5 value means that I will let it go down to half the original font size 
// before the texts gets truncated

// note, if using anything pre ios6, you would use I think
button.titleLabel.minimumFontSize = 8;

iOS Launching Settings -> Restrictions URL Scheme

In iOS 9 it works again!

To open Settings > General > Keyboard, I use:

prefs:root=General&path=Keyboard

Moreover, it is possible to go farther to Keyboards:

prefs:root=General&path=Keyboard/KEYBOARDS

How can I select rows with most recent timestamp for each key value?

This can de done in a relatively elegant way using SELECT DISTINCT, as follows:

SELECT DISTINCT ON (sensorID)
sensorID, timestamp, sensorField1, sensorField2 
FROM sensorTable
ORDER BY sensorID, timestamp DESC;

The above works for PostgreSQL (some more info here) but I think also other engines. In case it's not obvious, what this does is sort the table by sensor ID and timestamp (newest to oldest), and then returns the first row (i.e. latest timestamp) for each unique sensor ID.

In my use case I have ~10M readings from ~1K sensors, so trying to join the table with itself on a timestamp-based filter is very resource-intensive; the above takes a couple of seconds.

Saving excel worksheet to CSV files with filename+worksheet name using VB

The code above works perfectly with one minor flaw; the resulting file is not saved with a .csv extension. – Tensigh 2 days ago

I added the following to code and it saved my file as a csv. Thanks for this bit of code.It all worked as expected.

ActiveWorkbook.SaveAs Filename:=SaveToDirectory & ThisWorkbook.Name & "-" & WS.Name & ".csv", FileFormat:=xlCSV

Microsoft Visual C++ Compiler for Python 3.4

Visual Studio Community 2015 suffices to build extensions for Python 3.5. It's free but a 6 GB download (overkill). On my computer it installed vcvarsall at C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat

For Python 3.4 you'd need Visual Studio 2010. I don't think there's any free edition. See https://matthew-brett.github.io/pydagogue/python_msvc.html

Does HTTP use UDP?

Typically, no.

Streaming is seldom used over HTTP itself, and HTTP is seldom run over UDP. See, however, RTP.

For something as your example (in the comment), you're not showing a protocol for the resource. If that protocol were to be HTTP, then I wouldn't call the access "streaming"; even if it in some sense of the word is since it's sending a (possibly large) resource serially over a network. Typically, the resource will be saved to local disk before being played back, so the network transfer is not what's usually meant by "streaming".

As commenters have pointed out, though, it's certainly possible to really stream over HTTP, and that's done by some.

What is the difference between a .cpp file and a .h file?

Others have already offered good explanations, but I thought I should clarify the differences between the various extensions:

  Source Files for C: .c
  Header Files for C: .h

  Source Files for C++: .cpp
  Header Files for C++: .hpp

Of course, as it has already been pointed out, these are just conventions. The compiler doesn't actually pay any attention to them - it's purely for the benefit of the coder.

How to run server written in js with Node.js

If you are in a Linux container, such as on a Chromebook, you will need to manually browse to your localhost's address. I am aware the newer Chrome OS versions no longer have this problem, but on my Chromebook, I still had to manually browse to the localhost's address for your code to work.

To browse to your locahost's address, type this in command line: sudo ifconfig

and note the inet address under eth0.

Otherwise, as others have noted, simply type node.js filename and it will work as long as you point the browser to the proper address.

Hope this helps!

What does the explicit keyword mean?

The keyword explicit accompanies either

  • a constructor of class X that cannot be used to implicitly convert the first (any only) parameter to type X

C++ [class.conv.ctor]

1) A constructor declared without the function-specifier explicit specifies a conversion from the types of its parameters to the type of its class. Such a constructor is called a converting constructor.

2) An explicit constructor constructs objects just like non-explicit constructors, but does so only where the direct-initialization syntax (8.5) or where casts (5.2.9, 5.4) are explicitly used. A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or valueinitialization (8.5).

  • or a conversion function that is only considered for direct initialization and explicit conversion.

C++ [class.conv.fct]

2) A conversion function may be explicit (7.1.2), in which case it is only considered as a user-defined conversion for direct-initialization (8.5). Otherwise, user-defined conversions are not restricted to use in assignments and initializations.

Overview

Explicit conversion functions and constructors can only be used for explicit conversions (direct initialization or explicit cast operation) while non-explicit constructors and conversion functions can be used for implicit as well as explicit conversions.

/*
                                 explicit conversion          implicit conversion

 explicit constructor                    yes                          no

 constructor                             yes                          yes

 explicit conversion function            yes                          no

 conversion function                     yes                          yes

*/

Example using structures X, Y, Z and functions foo, bar, baz:

Let's look at a small setup of structures and functions to see the difference between explicit and non-explicit conversions.

struct Z { };

struct X { 
  explicit X(int a); // X can be constructed from int explicitly
  explicit operator Z (); // X can be converted to Z explicitly
};

struct Y{
  Y(int a); // int can be implicitly converted to Y
  operator Z (); // Y can be implicitly converted to Z
};

void foo(X x) { }
void bar(Y y) { }
void baz(Z z) { }

Examples regarding constructor:

Conversion of a function argument:

foo(2);                     // error: no implicit conversion int to X possible
foo(X(2));                  // OK: direct initialization: explicit conversion
foo(static_cast<X>(2));     // OK: explicit conversion

bar(2);                     // OK: implicit conversion via Y(int) 
bar(Y(2));                  // OK: direct initialization
bar(static_cast<Y>(2));     // OK: explicit conversion

Object initialization:

X x2 = 2;                   // error: no implicit conversion int to X possible
X x3(2);                    // OK: direct initialization
X x4 = X(2);                // OK: direct initialization
X x5 = static_cast<X>(2);   // OK: explicit conversion 

Y y2 = 2;                   // OK: implicit conversion via Y(int)
Y y3(2);                    // OK: direct initialization
Y y4 = Y(2);                // OK: direct initialization
Y y5 = static_cast<Y>(2);   // OK: explicit conversion

Examples regarding conversion functions:

X x1{ 0 };
Y y1{ 0 };

Conversion of a function argument:

baz(x1);                    // error: X not implicitly convertible to Z
baz(Z(x1));                 // OK: explicit initialization
baz(static_cast<Z>(x1));    // OK: explicit conversion

baz(y1);                    // OK: implicit conversion via Y::operator Z()
baz(Z(y1));                 // OK: direct initialization
baz(static_cast<Z>(y1));    // OK: explicit conversion

Object initialization:

Z z1 = x1;                  // error: X not implicitly convertible to Z
Z z2(x1);                   // OK: explicit initialization
Z z3 = Z(x1);               // OK: explicit initialization
Z z4 = static_cast<Z>(x1);  // OK: explicit conversion

Z z1 = y1;                  // OK: implicit conversion via Y::operator Z()
Z z2(y1);                   // OK: direct initialization
Z z3 = Z(y1);               // OK: direct initialization
Z z4 = static_cast<Z>(y1);  // OK: explicit conversion

Why use explicit conversion functions or constructors?

Conversion constructors and non-explicit conversion functions may introduce ambiguity.

Consider a structure V, convertible to int, a structure U implicitly constructible from V and a function f overloaded for U and bool respectively.

struct V {
  operator bool() const { return true; }
};

struct U { U(V) { } };

void f(U) { }
void f(bool) {  }

A call to f is ambiguous if passing an object of type V.

V x;
f(x);  // error: call of overloaded 'f(V&)' is ambiguous

The compiler does not know wether to use the constructor of U or the conversion function to convert the V object into a type for passing to f.

If either the constructor of U or the conversion function of V would be explicit, there would be no ambiguity since only the non-explicit conversion would be considered. If both are explicit the call to f using an object of type V would have to be done using an explicit conversion or cast operation.

Conversion constructors and non-explicit conversion functions may lead to unexpected behaviour.

Consider a function printing some vector:

void print_intvector(std::vector<int> const &v) { for (int x : v) std::cout << x << '\n'; }

If the size-constructor of the vector would not be explicit it would be possible to call the function like this:

print_intvector(3);

What would one expect from such a call? One line containing 3 or three lines containing 0? (Where the second one is what happens.)

Using the explicit keyword in a class interface enforces the user of the interface to be explicit about a desired conversion.

As Bjarne Stroustrup puts it (in "The C++ Programming Language", 4th Ed., 35.2.1, pp. 1011) on the question why std::duration cannot be implicitly constructed from a plain number:

If you know what you mean, be explicit about it.

text-align: right on <select> or <option>

The following CSS will right-align both the arrow and the options:

_x000D_
_x000D_
select { text-align-last: right; }_x000D_
option { direction: rtl; }
_x000D_
<!-- example usage -->_x000D_
Choose one: <select>_x000D_
  <option>The first option</option>_x000D_
  <option>A second, fairly long option</option>_x000D_
  <option>Last</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

git: patch does not apply

git apply --reject --whitespace=fix mychanges.patch worked for me.

Explanation

The --reject option will instruct git to not fail if it cannot determine how to apply a patch, but instead to apply indivdual hunks it can apply and create reject files (.rej) for hunks it cannot apply. Wiggle can "apply [these] rejected patches and perform word-wise diffs".

Additionally, --whitespace=fix will warn about whitespace errors and try to fix them, rather than refusing to apply an otherwise applicable hunk.

Both options together make the application of a patch more robust against failure, but they require additional attention with respect to the result.

For the whole documentation, see https://git-scm.com/docs/git-apply.

JavaScript DOM remove element

In most browsers, there's a slightly more succinct way of removing an element from the DOM than calling .removeChild(element) on its parent, which is to just call element.remove(). In due course, this will probably become the standard and idiomatic way of removing an element from the DOM.

The .remove() method was added to the DOM Living Standard in 2011 (commit), and has since been implemented by Chrome, Firefox, Safari, Opera, and Edge. It was not supported in any version of Internet Explorer.

If you want to support older browsers, you'll need to shim it. This turns out to be a little irritating, both because nobody seems to have made a all-purpose DOM shim that contains these methods, and because we're not just adding the method to a single prototype; it's a method of ChildNode, which is just an interface defined by the spec and isn't accessible to JavaScript, so we can't add anything to its prototype. So we need to find all the prototypes that inherit from ChildNode and are actually defined in the browser, and add .remove to them.

Here's the shim I came up with, which I've confirmed works in IE 8.

(function () {
    var typesToPatch = ['DocumentType', 'Element', 'CharacterData'],
        remove = function () {
            // The check here seems pointless, since we're not adding this
            // method to the prototypes of any any elements that CAN be the
            // root of the DOM. However, it's required by spec (see point 1 of
            // https://dom.spec.whatwg.org/#dom-childnode-remove) and would
            // theoretically make a difference if somebody .apply()ed this
            // method to the DOM's root node, so let's roll with it.
            if (this.parentNode != null) {
                this.parentNode.removeChild(this);
            }
        };

    for (var i=0; i<typesToPatch.length; i++) {
        var type = typesToPatch[i];
        if (window[type] && !window[type].prototype.remove) {
            window[type].prototype.remove = remove;
        }
    }
})();

This won't work in IE 7 or lower, since extending DOM prototypes isn't possible before IE 8. I figure, though, that on the verge of 2015 most people needn't care about such things.

Once you've included them shim, you'll be able to remove a DOM element element from the DOM by simply calling

element.remove();

How to set max width of an image in CSS

Given your container width 600px.

If you want only bigger images than that to fit inside, add: CSS:

#ImageContainer img {
    max-width: 600px;
}

If you want ALL images to take the avaiable (600px) space:

#ImageContainer img {
    width: 600px;
}

Get rid of "The value for annotation attribute must be a constant expression" message

The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

See also here: How to supply value to an annotation from a Constant java

It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

Javascript one line If...else...else if statement

This is use mostly for assigning variable, and it uses binomial conditioning eg.

var time = Date().getHours(); // or something

var clockTime = time > 12 ? 'PM' : 'AM' ;

There is no ElseIf, for the sake of development don't use chaining, you can use switch which is much faster if you have multiple conditioning in .js

How to change the default charset of a MySQL table?

The ALTER TABLE MySQL command should do the trick. The following command will change the default character set of your table and the character set of all its columns to UTF8.

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

This command will convert all text-like columns in the table to the new character set. Character sets use different amounts of data per character, so MySQL will convert the type of some columns to ensure there's enough room to fit the same number of characters as the old column type.

I recommend you read the ALTER TABLE MySQL documentation before modifying any live data.

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

you can try this: adb install -r -d -f your_Apk_path

How do I encrypt and decrypt a string in python?

Encrypt Data

First, we need to install the cryptography library:

pip3 install cryptography
  • From the cryptography library, we need to import Fernet and start generating a key - this key is required for symmetric encryption/decryption.

  • To generate a key, we call the generate_key() method.

    • We only need to execute the above method once to generate a key.

    You need to keep this key in a safe place. If you lose the key, you won't be able to decrypt the data that was encrypted with this key.

  • Once we have generated a key, we need to load the key with load_key()

Encrypt a Message

This is a three step process:

  1. encode the message
  2. initialize the Fernet class
  3. pass the encoded message to encrypt() method

Below is a full working example of encrypting a message :

from cryptography.fernet import Fernet

def generate_key():
    """
    Generates a key and save it into a file
    """
    key = Fernet.generate_key()
    with open("secret.key", "wb") as key_file:
        key_file.write(key)

def load_key():
    """
    Load the previously generated key
    """
    return open("secret.key", "rb").read()

def encrypt_message(message):
    """
    Encrypts a message
    """
    key = load_key()
    encoded_message = message.encode()
    f = Fernet(key)
    encrypted_message = f.encrypt(encoded_message)

    print(encrypted_message)

if __name__ == "__main__":
    # generate_key() # execute only once 
    encrypt_message("Hello stackoverflow!")

output:

b'gAAAAABgLX7Zj-kn-We2BI_c9NQhEtfJEnHUVhVqtiqjkDi5dgJafj-_8QUDyeNS2zsJTdBWg6SntRJOjOM1U5mIxxsGny7IEGqpVVdHwheTnwzSBlgpb80='

Decrypt Data

To decrypt the message, we just call the decrypt() method from the Fernet library. Remember, we also need to load the key as well, because the key is needed to decrypt the message.

from cryptography.fernet import Fernet

def load_key():
    """
    Load the previously generated key
    """
    return open("secret.key", "rb").read()

def decrypt_message(encrypted_message):
    """
    Decrypts an encrypted message
    """
    key = load_key()
    f = Fernet(key)
    decrypted_message = f.decrypt(encrypted_message)

    print(decrypted_message.decode())

if __name__ == "__main__":
    decrypt_message(b'gAAAAABgLX7Zj-kn-We2BI_c9NQhEtfJEnHUVhVqtiqjkDi5dgJafj-_8QUDyeNS2zsJTdBWg6SntRJOjOM1U5mIxxsGny7IEGqpVVdHwheTnwzSBlgpb80=')

output:

Hello stackoverflow!


Your password is in the secret.key in a form similar to the password below:

B8wtXqwBA_zb2Iaz5pW8CIQIwGSYSFoBiLsVz-vTqzw=

FIFO based Queue implementations?

Here is example code for usage of java's built-in FIFO queue:

public static void main(String[] args) {
    Queue<Integer> myQ = new LinkedList<Integer>();
    myQ.add(1);
    myQ.add(6);
    myQ.add(3);
    System.out.println(myQ);   // 1 6 3
    int first = myQ.poll();    // retrieve and remove the first element
    System.out.println(first); // 1
    System.out.println(myQ);   // 6 3
}

how to create a logfile in php?

To write to a log file and make a new one each day, you could use date("j.n.Y") as part of the filename.

//Something to write to txt log
$log  = "User: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
        "Attempt: ".($result[0]['success']=='1'?'Success':'Failed').PHP_EOL.
        "User: ".$username.PHP_EOL.
        "-------------------------".PHP_EOL;
//Save string to log, use FILE_APPEND to append.
file_put_contents('./log_'.date("j.n.Y").'.log', $log, FILE_APPEND);

So you would place that within your hasAccess() method.

public function hasAccess($username,$password){
    $form = array();
    $form['username'] = $username;
    $form['password'] = $password;

    $securityDAO = $this->getDAO('SecurityDAO');
    $result = $securityDAO->hasAccess($form);

    //Write action to txt log
    $log  = "User: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
            "Attempt: ".($result[0]['success']=='1'?'Success':'Failed').PHP_EOL.
            "User: ".$username.PHP_EOL.
            "-------------------------".PHP_EOL;
    //-
    file_put_contents('./log_'.date("j.n.Y").'.txt', $log, FILE_APPEND);

    if($result[0]['success']=='1'){
        $this->Session->add('user_id', $result[0]['id']);
        //$this->Session->add('username', $result[0]['username']);
        //$this->Session->add('roleid', $result[0]['roleid']);
        return $this->status(0,true,'auth.success',$result);
    }else{
        return $this->status(0,false,'auth.failed',$result);
    }
}

how to access iFrame parent page using jquery?

There are multiple ways to do these.

I) Get main parent directly.

for exa. i want to replace my child page to iframe then

var link = '<%=Page.ResolveUrl("~/Home/SubscribeReport")%>';
top.location.replace(link);

here top.location gets parent directly.

II) get parent one by one,

var element = $('.iframe:visible', window.parent.document);

here if you have more then one iframe, then specify active or visible one.

you also can do like these for getting further parents,

var masterParent = element.parent().parent().parent()

III) get parent by Identifier.

var myWindow = window.top.$("#Identifier")

Relative path to absolute path in C#?

Assuming you know the real directory the XML file lives in use Path.Combine, e.g.

var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");

If you want to get back the full path with any ..'s collapsed then you can use:

Path.GetFullPath((new Uri(absolute_path)).LocalPath);

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

How to send json data in the Http request using NSURLRequest

You can try this code for send json string

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:@"www.test.com?xyz.php&param=%@",jsonString];

How to get current time in python and break up into year, month, day, hour, minute?

The datetime module is your friend:

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40

You don't need separate variables, the attributes on the returned datetime object have all you need.

Get element inside element by class and ID - JavaScript

Recursive function :

function getElementInsideElement(baseElement, wantedElementID) {
    var elementToReturn;
    for (var i = 0; i < baseElement.childNodes.length; i++) {
        elementToReturn = baseElement.childNodes[i];
        if (elementToReturn.id == wantedElementID) {
            return elementToReturn;
        } else {
            return getElementInsideElement(elementToReturn, wantedElementID);
        }
    }
}

Capitalize the first letter of string in AngularJs

For the AngularJS from meanjs.org, I place the custom filters in modules/core/client/app/init.js

I needed a custom filter to capitalize each word in a sentence, here is how I do so:

angular.module(ApplicationConfiguration.applicationModuleName).filter('capitalize', function() {
return function(str) {
    return str.split(" ").map(function(input){return (!!input) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() :         ''}).join(" ");

}
});

The credit of the map function goes to @Naveen raj

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

I had the same issue, my problem was that the firewall on the server wasn't open from the current ip address.

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

Have similar issue this morning and following way saved my life:

Did you try to turn off the innodb_strict_mode?

SET GLOBAL innodb_strict_mode = 0;

and then try to import it again.

innodb_strict_mode is ON using MySQL >= 5.7.7, before it was OFF.

What is a 'workspace' in Visual Studio Code?

As of May 2018, it seems that a workspace in Visual Studio Code allows you to have quick access to different but related projects. All without having to open a different folder.

And you can have multiple workspaces too. See references here and you will get the full picture of it:

Reference 1
Reference 2

Spring Boot Configure and Use Two DataSources

@Primary annotation when used against a method like below works good if the two data sources are on the same db location/server.

@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
  return DataSourceBuilder.create().build();
}

@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
  return DataSourceBuilder.create().build();
}

If the data sources are on different servers its better to use @Component along with @Primary annotation. The following code snippet works well on two different data sources at different locations

database1.datasource.url = jdbc:mysql://127.0.0.1:3306/db1
database1.datasource.username = root
database1.datasource.password = mysql
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

database2.datasource1.url = jdbc:mysql://192.168.113.51:3306/db2
database2.datasource1.username = root
database2.datasource1.password = mysql
database2.datasource1.driver-class-name=com.mysql.jdbc.Driver

@Configuration
@Primary
@Component
@ComponentScan("com.db1.bean")
class DBConfiguration1{
    @Bean("db1Ds")
    @ConfigurationProperties(prefix="database1.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

}

@Configuration
@Component
@ComponentScan("com.db2.bean")
class DBConfiguration2{
    @Bean("db2Ds")
    @ConfigurationProperties(prefix="database2.datasource1")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

}

Create <div> and append <div> dynamically

var iDiv = document.createElement('div');

iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

var div2 = document.createElement('div');

div2.className = 'block-2';
iDiv.appendChild(div2);

GZIPInputStream reading line by line

GZIPInputStream gzip = new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"));
BufferedReader br = new BufferedReader(new InputStreamReader(gzip));
br.readLine();

How do I get the opposite (negation) of a Boolean in Python?

If you are trying to implement a toggle, so that anytime you re-run a persistent code its being negated, you can achieve that as following:

try:
    toggle = not toggle
except NameError:
    toggle = True

Running this code will first set the toggle to True and anytime this snippet ist called, toggle will be negated.

Detect element content changes with jQuery

You can add a callback option to html (,or any) function:

$.fn.oldHtml = $.fn.html;
$.fn.html = function(html,fn){
  fn = fn || function(){};
  var result =  this.oldHtml(html);
  fn();
  return result;
};
$('body').html(11,function(){alert("haha");});

Demo here.

You do the change on some element, not the element is forced to change by something that you have to catch.

How to read XML using XPath in Java

You need something along the lines of this:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(<xpath_expression>);

Then you call expr.evaluate() passing in the document defined in that code and the return type you are expecting, and cast the result to the object type of the result.

If you need help with a specific XPath expressions, you should probably ask it as separate questions (unless that was your question in the first place here - I understood your question to be how to use the API in Java).

Edit: (Response to comment): This XPath expression will get you the text of the first URL element under PowerBuilder:

/howto/topic[@name='PowerBuilder']/url/text()

This will get you the second:

/howto/topic[@name='PowerBuilder']/url[2]/text()

You get that with this code:

expr.evaluate(doc, XPathConstants.STRING);

If you don't know how many URLs are in a given node, then you should rather do something like this:

XPathExpression expr = xpath.compile("/howto/topic[@name='PowerBuilder']/url");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

And then loop over the NodeList.

IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

The problem is with your line

x=np.array ([x0*n])

Here you define x as a single-item array of -200.0. You could do this:

x=np.array ([x0,]*n)

or this:

x=np.zeros((n,)) + x0

Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single

from pylab import *

line in the top you could use all the modules you need.