问:
CSS percentage width not working
I've been trying to edit the CSS for my website's navbar in order to transform it from having fixed width and height values into percentage values (in order for it to become responsive and work better with different screen sizes). However, when I converted the values, the individual divs didn't correctly size.

There is probably something very simple that I've missed here (seeing as I am a self taught amateur in CSS and HTML), but I couldn't find any solutions here.

This is a JSfiddle of my naviation bar using px, working properly

This is a JSfiddle of it after conversion to percentage values for width.

Relevant code (post conversion):

HTML:

```<code><body>
<div id="container">
    <div id="menuwrap">
        <ul id="menu">
        <li id="one"><a href="#"><h class="navbartext">one</h></a></li>
        <li id="two"><a href="#"><h class="navbartext">two</h></a></li>
        <li id="three"><a href="#"><h class="navbartext">three</h></a></li>
        <li id="four"><a href="#"><h class="navbartext">four</h></a></li>
        <li id="five"><a href="#"><h class="navbartext">five</h></a></li>
        <li id="six"><a href="#"><h class="navbartext">six</h></a></li>
        <li id="seven"><a href="#"></a></li>
        </ul>
    </div>
</div>
</body>
</code>```

CSS:

```<code>#container {
    width:100%;
    height:25px;
    margin:0 auto;
    background:#fff;
}

#menuwrap {
    height:25px;
    width:100%
    position:relative;
    top:25px;
    background:#fff;
}

ul#menu {
    height:25px;
    float:right;
    margin:0;
    padding:0;
    list-style-type:none;
    background:#44546A;
}

ul#menu li {
    float:left;
}

ul#menu li a {
    display: block;
    width: auto;
    height:25px;
    overflow:hidden;
    text-indent:10px;
    background:#000;
    color:#000;
}

ul#menu li#one a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#two a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#three a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#four a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#five a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#six a {
    width:17%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#seven a {
    width: 49px;
    height: 49px;
    -webkit-border-radius: 25px;
    -moz-border-radius: 25px;
    border-radius: 25px;
    background-color:#000;
    border-style: solid;
    border-width: 1px;
    border-color: #fff;
    position:relative;
    top: -17.5px;
    left:88%;
    z-index:2;
}

ul#menu li class.a
{
width:208px;
margin:0px;
}
</code>```

答:
My web-design book, Murach's HTML5 and CSS3 3rd edition says to use slickNav for a responsive menu. It is a Javascript plugin. Also, I have just fixed my problem sort of. I was attempting to size the blocked  elements when I should have been sizing their containers. Here is some sample code

```<code>nav {width:100%;}

nav #nav_menu {
    list-style-type: none;
    padding: 0%;
    margin: 0%;
}

 #nav_menu > li {
    float: left;
    width:20%;
    max-width: 190px;
}
</code>```

Hope this helps.

Title: CSS percentage width not working

Body:
I've been trying to edit the CSS for my website's navbar in order to transform it from having fixed width and height values into percentage values (in order for it to become responsive and work better with different screen sizes). However, when I converted the values, the individual divs didn't correctly size.

There is probably something very simple that I've missed here (seeing as I am a self taught amateur in CSS and HTML), but I couldn't find any solutions here.

This is a JSfiddle of my naviation bar using px, working properly

This is a JSfiddle of it after conversion to percentage values for width.

Relevant code (post conversion):

HTML:

<h class="navbartext">one</h>

<h class="navbartext">two</h>

<h class="navbartext">three</h>

<h class="navbartext">four</h>

<h class="navbartext">five</h>

<h class="navbartext">six</h>

CSS:

#container {
    width:100%;
    height:25px;
    margin:0 auto;
    background:#fff;
}

#menuwrap {
    height:25px;
    width:100%
    position:relative;
    top:25px;
    background:#fff;
}

ul#menu {
    height:25px;
    float:right;
    margin:0;
    padding:0;
    list-style-type:none;
    background:#44546A;
}

ul#menu li {
    float:left;
}

ul#menu li a {
    display: block;
    width: auto;
    height:25px;
    overflow:hidden;
    text-indent:10px;
    background:#000;
    color:#000;
}

ul#menu li#one a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#two a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#three a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#four a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#five a {
    width:16.6%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#six a {
    width:17%;
    text-align:center;
    vertical-align: middle;
}

ul#menu li#seven a {
    width: 49px;
    height: 49px;
    -webkit-border-radius: 25px;
    -moz-border-radius: 25px;
    border-radius: 25px;
    background-color:#000;
    border-style: solid;
    border-width: 1px;
    border-color: #fff;
    position:relative;
    top: -17.5px;
    left:88%;
    z-index:2;
}

ul#menu li class.a
{
width:208px;
margin:0px;
}

Body:
My web-design book, Murach's HTML5 and CSS3 3rd edition says to use slickNav for a responsive menu. It is a Javascript plugin. Also, I have just fixed my problem sort of. I was attempting to size the blocked  elements when I should have been sizing their containers. Here is some sample code

nav {width:100%;}

nav #nav_menu {
    list-style-type: none;
    padding: 0%;
    margin: 0%;
}

 #nav_menu > li {
    float: left;
    width:20%;
    max-width: 190px;
}

Hope this helps.


来源: stackexchange

问:
conversion from NSTimeInterval to hour,minutes,seconds,milliseconds in swift
My code is here:

```<code>func stringFromTimeInterval(interval:NSTimeInterval) -> NSString {

    var ti = NSInteger(interval)
    var ms = ti * 1000
    var seconds = ti % 60
    var minutes = (ti / 60) % 60
    var hours = (ti / 3600)

      return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds,ms)
}
</code>```

in output the milliseconds give wrong result.Please give an idea how to find milliseconds correctly.

答:
SWIFT 3 Extension

I think this way is a easier to see where each piece comes from so you can more easily modify it to your needs

```<code>extension TimeInterval {
    private var milliseconds: Int {
        return Int((truncatingRemainder(dividingBy: 1)) * 1000)
    }

    private var seconds: Int {
        return Int(self) % 60
    }

    private var minutes: Int {
        return (Int(self) / 60 ) % 60
    }

    private var hours: Int {
        return Int(self) / 3600
    }

    var stringTime: String {
        if hours != 0 {
            return "\(hours)h \(minutes)m \(seconds)s"
        } else if minutes != 0 {
            return "\(minutes)m \(seconds)s"
        } else if milliseconds != 0 {
            return "\(seconds)s \(milliseconds)ms"
        } else {
            return "\(seconds)s"
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My code is here:

func stringFromTimeInterval(interval:NSTimeInterval) -> NSString {

    var ti = NSInteger(interval)
    var ms = ti * 1000
    var seconds = ti % 60
    var minutes = (ti / 60) % 60
    var hours = (ti / 3600)

      return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds,ms)
}

in output the milliseconds give wrong result.Please give an idea how to find milliseconds correctly.

Body:
SWIFT 3 Extension

I think this way is a easier to see where each piece comes from so you can more easily modify it to your needs

extension TimeInterval {
    private var milliseconds: Int {
        return Int((truncatingRemainder(dividingBy: 1)) * 1000)
    }

    private var seconds: Int {
        return Int(self) % 60
    }

    private var minutes: Int {
        return (Int(self) / 60 ) % 60
    }

    private var hours: Int {
        return Int(self) / 3600
    }

    var stringTime: String {
        if hours != 0 {
            return "\(hours)h \(minutes)m \(seconds)s"
        } else if minutes != 0 {
            return "\(minutes)m \(seconds)s"
        } else if milliseconds != 0 {
            return "\(seconds)s \(milliseconds)ms"
        } else {
            return "\(seconds)s"
        }
    }
}


问:
Loading external JavaScript file
I have a cross platform app built using PhoneGap/Cordova.

I am trying to implement a function that runs an external JavaScript file when a controller loads. I am following a solution from HERE. And similarly HERE. But I want the JavaScript to execute without the window.open event, i.e. I want to run executeScript as soon as the device is ready.

How do I call the executeScript() without defining the var ref first though?

```<code>var navigation = angular.module("navigation", []);
navigation.controller("Navigation", function ($scope) {

    var init = function () {
        document.addEventListener("deviceready", onDeviceReady, false);
    };

    init();

    function onDeviceReady() {
        // LOAD EXTERNAL SCRIPT
        var ref = window.open('http://www.haruair.com/', '_blank', 'location=yes, toolbar=yes, EnableViewPortScale=yes');
        ref.addEventListener("loadstop", function () {
            ref.executeScript(
              { file: 'http://haruair.com/externaljavascriptfile.js' },
              function () {
                  ref.executeScript(
                    { code: 'getSomething()' },
                    function (values) {
                        var data = values[0];
                        alert("Name: " + data.name + "\nAge: "  + data.age);
                    });
              }
            );
        });
});
</code>```

答:
You could try to add the script in the index.html file and do whatever you want from JS. Also, you must add to your whitelist this endpoint.

```<code><!-- index.html -->

<script>
  function onCustomLoad() {
    //do stuff
  }
</script>
<script src="your-custom-script" onload="onCustomLoad"></script>
</code>```

Title: Loading external JavaScript file

Body:
I have a cross platform app built using PhoneGap/Cordova.

I am trying to implement a function that runs an external JavaScript file when a controller loads. I am following a solution from HERE. And similarly HERE. But I want the JavaScript to execute without the window.open event, i.e. I want to run executeScript as soon as the device is ready.

How do I call the executeScript() without defining the var ref first though?

var navigation = angular.module("navigation", []);
navigation.controller("Navigation", function ($scope) {

    var init = function () {
        document.addEventListener("deviceready", onDeviceReady, false);
    };

    init();

    function onDeviceReady() {
        // LOAD EXTERNAL SCRIPT
        var ref = window.open('http://www.haruair.com/', '_blank', 'location=yes, toolbar=yes, EnableViewPortScale=yes');
        ref.addEventListener("loadstop", function () {
            ref.executeScript(
              { file: 'http://haruair.com/externaljavascriptfile.js' },
              function () {
                  ref.executeScript(
                    { code: 'getSomething()' },
                    function (values) {
                        var data = values[0];
                        alert("Name: " + data.name + "\nAge: "  + data.age);
                    });
              }
            );
        });
});

Body:
You could try to add the script in the index.html file and do whatever you want from JS. Also, you must add to your whitelist this endpoint.

<!-- index.html -->

<script>
  function onCustomLoad() {
    //do stuff
  }
</script>
<script src="your-custom-script" onload="onCustomLoad"></script>


问:
Is it bad practice to return from within a try catch finally block?
So I came across some code this morning that looked like this:

```<code>try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}
</code>```

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

答:
This may answer your question

What really happens in a try { return x; } finally { x = null; } statement?

From reading that question it sounds like you can have another try catch structure in the finally statement if you think it might throw an exception. The compiler will figure out when to return the value.

That said, it might be better to restructure your code anyway just so it doesn't confuse you later on or someone else who may be unaware of this as well.

OwnerDisplayName: lomaxx

Body:
So I came across some code this morning that looked like this:

try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

OwnerDisplayName: Spencer Ruport

ContentLicense: CC BY-SA 2.5


问:
Grid of Checkboxes in WPF
I have a WPF UserControl's datacontext tied to a class like this:

```<code>public class CheckBoxGridViewModel
{
  public List<List<bool>> Checkboxes {get; set;}
}
</code>```

I want it to display a grid of checkboxes. I'm assuming I can use an Itemscontrol, but don't know exactly how to do it with a dynamic set of columns for each row.

This question seems to answer mine, except the answer didn't give the example and I can't figure how to write it out.

So the question is, how would I write the xaml to display the checkboxes of the Checkboxes property so that they are lined up in a nice grid?

The outer list would be each row and the inner list would be each column of the row.

答:
See this question. The answer by Jobi Joy will let you present the 2D list but Binding won't work so you can't edit your values.

To be able to bind the values you can use a helper class like this

```<code>public static class BindableListHelper
{
    public static List<List<Ref<T>>> GetBindable2DList<T>(List<List<T>> list)
    {
        List<List<Ref<T>>> refInts = new List<List<Ref<T>>>();

        for (int i = 0; i < list.Count; i++)
        {
            refInts.Add(new List<Ref<T>>());
            for (int j = 0; j < list[i].Count; j++)
            {
                int a = i;
                int b = j;
                refInts[i].Add(new Ref<T>(() => list[a][b], z => { list[a][b] = z; }));
            }
        }
        return refInts;
    }
}
</code>```

This method uses this Ref class

```<code>public class Ref<T>
{
    private readonly Func<T> getter;
    private readonly Action<T> setter;
    public Ref(Func<T> getter, Action<T> setter)
    {
        this.getter = getter;
        this.setter = setter;
    }
    public T Value { get { return getter(); } set { setter(value); } }
}
</code>```

Then you can set ItemsSource for the ItemsControl with

```<code>itemsControl.ItemsSource = BindableListHelper.GetBindable2DList<bool>(Checkboxes);
</code>```

and the editing should work

Using the same code as Jobi Joy from the question I linked, you can change the Button in DataTemplate_Level2 to a CheckBox and bind IsChecked for it to Value instead (since it will point to the Ref class otherwise)

```<code><Window.Resources>
    <DataTemplate x:Key="DataTemplate_Level2">
        <CheckBox IsChecked="{Binding Path=Value}" Height="15" Width="15" Margin="2"/>
    </DataTemplate>
    <DataTemplate x:Key="DataTemplate_Level1">
        <ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource DataTemplate_Level2}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </DataTemplate>
</Window.Resources>
<StackPanel>
    <Border HorizontalAlignment="Left" BorderBrush="Black" BorderThickness="2">
        <ItemsControl x:Name="itemsControl" ItemTemplate="{DynamicResource DataTemplate_Level1}"/>
    </Border>
</StackPanel>
</code>```

Without setting the Content property for the CheckBox it'll look something like this

Title: Grid of Checkboxes in WPF

Body:
I have a WPF UserControl's datacontext tied to a class like this:

public class CheckBoxGridViewModel
{
  public List<List<bool>> Checkboxes {get; set;}
}

I want it to display a grid of checkboxes. I'm assuming I can use an Itemscontrol, but don't know exactly how to do it with a dynamic set of columns for each row.

This question seems to answer mine, except the answer didn't give the example and I can't figure how to write it out.

So the question is, how would I write the xaml to display the checkboxes of the Checkboxes property so that they are lined up in a nice grid?

The outer list would be each row and the inner list would be each column of the row.

Body:
See this question. The answer by Jobi Joy will let you present the 2D list but Binding won't work so you can't edit your values.

To be able to bind the values you can use a helper class like this

public static class BindableListHelper
{
    public static List<List<Ref<T>>> GetBindable2DList<T>(List<List<T>> list)
    {
        List<List<Ref<T>>> refInts = new List<List<Ref<T>>>();

        for (int i = 0; i < list.Count; i++)
        {
            refInts.Add(new List<Ref<T>>());
            for (int j = 0; j < list[i].Count; j++)
            {
                int a = i;
                int b = j;
                refInts[i].Add(new Ref<T>(() => list[a][b], z => { list[a][b] = z; }));
            }
        }
        return refInts;
    }
}

This method uses this Ref class

public class Ref<T>
{
    private readonly Func<T> getter;
    private readonly Action<T> setter;
    public Ref(Func<T> getter, Action<T> setter)
    {
        this.getter = getter;
        this.setter = setter;
    }
    public T Value { get { return getter(); } set { setter(value); } }
}

Then you can set ItemsSource for the ItemsControl with

itemsControl.ItemsSource = BindableListHelper.GetBindable2DList<bool>(Checkboxes);

and the editing should work

Using the same code as Jobi Joy from the question I linked, you can change the Button in DataTemplate_Level2 to a CheckBox and bind IsChecked for it to Value instead (since it will point to the Ref class otherwise)

<Window.Resources>
    <DataTemplate x:Key="DataTemplate_Level2">
        <CheckBox IsChecked="{Binding Path=Value}" Height="15" Width="15" Margin="2"/>
    </DataTemplate>
    <DataTemplate x:Key="DataTemplate_Level1">
        <ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource DataTemplate_Level2}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </DataTemplate>
</Window.Resources>
<StackPanel>
    <Border HorizontalAlignment="Left" BorderBrush="Black" BorderThickness="2">
        <ItemsControl x:Name="itemsControl" ItemTemplate="{DynamicResource DataTemplate_Level1}"/>
    </Border>
</StackPanel>

Without setting the Content property for the CheckBox it'll look something like this


问:
can't find translation in admin or language file in prestashop
I'm working on a prestashop that has been customized before. I'm trying to add a translation for a head title but can't translate it.
This is the line in the .tpl file :

```<code><h4>{l s="saison" m="homefeatured"}</h4>
</code>```

I tried to add myself this in the languages php files

```<code>$_MODULE['<{homefeatured}nop>homefeatured_62d8617d49c4cbd03664e39af6f0fe2f'] = 'SEASONS';
</code>```

But it doesn't work and I can't find it it the admin > locations > translations > module name. I mean I see all other sentences that were here already but not this new one.

答:
Dummy, I found the solution.

```<code><h4>{l s="saison" m="homefeatured"}</h4>
</code>```

becomes

```<code><h4>{l s='saison' mod='homefeatured'}</h4>
</code>```

Body:
I'm working on a prestashop that has been customized before. I'm trying to add a translation for a head title but can't translate it.
This is the line in the .tpl file :

{l s="saison" m="homefeatured"}

I tried to add myself this in the languages php files

$_MODULE['<{homefeatured}nop>homefeatured_62d8617d49c4cbd03664e39af6f0fe2f'] = 'SEASONS';

But it doesn't work and I can't find it it the admin > locations > translations > module name. I mean I see all other sentences that were here already but not this new one.

Body:
Dummy, I found the solution.

<h4>{l s="saison" m="homefeatured"}</h4>

becomes

<h4>{l s='saison' mod='homefeatured'}</h4>


问:
Rails complete quickly but it takes longer to finish loading the page
I've been running with this problem lately. I can spot the following in server console:

Completed 200 OK in 2748ms (Views: 0.2ms | ActiveRecord: 42.8ms)

As you can see active record and views takes less than a second but still takes around 4 second to get a response from the server. I've run multiple Active record optimization but I can't find why does it take that long to see it.

答:
Give rack-mini-profiler a try.

Middleware that displays speed badge for every html page. Designed to work both in production and in development.

Features:

Database profiling - Currently supports Mysql2, Postgres, Oracle (oracle_enhanced ~> 1.5.0) and Mongoid3 (with fallback support to ActiveRecord)

  Call-stack profiling - Flame graphs showing time spent by gem

  Memory profiling - Per-request memory usage, GC stats, and global allocation metrics


问:
Python - how to get the value at a memory address?
I am trying to make Python get the value/data from an address such as 0x101BFFDC, which I found by using a cheat engine for a game. I've done much research and believe that I need to use ReadProcessMemory. However, I have tried several examples without success.

For example, I found the following code:

```<code>from ctypes import *
from ctypes.wintypes import *
import struct

OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory
CloseHandle = windll.kernel32.CloseHandle

PROCESS_ALL_ACCESS = 0x1F0FFF

pid = 10684 # pid of the game
address = 0x101BFFDC # I put the address here

buffer = c_char_p(b"The data goes here")
val = c_int()
bufferSize = len(buffer.value)
bytesRead = c_ulong(0)

processHandle = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
if ReadProcessMemory(processHandle, address, buffer, bufferSize, byref(bytesRead)):
    memmove(ctypes.byref(val), buffer, ctypes.sizeof(val))
    print("Success:" + str(val.value))
else:
    print("Failed.")

CloseHandle(processHandle)
</code>```

I expect it to give me the value 56, which is what I get from the cheat engine. However, it just prints "Failed." every time.

How can I get the value right?

答:
Here's a ctypes wrapper for WinAPI ReadProcessMemory. It takes the process ID, base address, and size in bytes to read. It returns the byte string read from the target process.

If allow_partial is false, the entire address range must be readable, else it fails with the Windows error code ERROR_PARTIAL_COPY. If allow_partial is true, the returned byte string may be less the number of requested bytes.

ctypes definitions

```<code>import ctypes
from ctypes import wintypes

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

ERROR_PARTIAL_COPY = 0x012B
PROCESS_VM_READ = 0x0010

SIZE_T = ctypes.c_size_t
PSIZE_T = ctypes.POINTER(SIZE_T)

def _check_zero(result, func, args):
    if not result:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

kernel32.OpenProcess.errcheck = _check_zero
kernel32.OpenProcess.restype = wintypes.HANDLE
kernel32.OpenProcess.argtypes = (
    wintypes.DWORD, # _In_ dwDesiredAccess
    wintypes.BOOL,  # _In_ bInheritHandle
    wintypes.DWORD) # _In_ dwProcessId

kernel32.ReadProcessMemory.errcheck = _check_zero
kernel32.ReadProcessMemory.argtypes = (
    wintypes.HANDLE,  # _In_  hProcess
    wintypes.LPCVOID, # _In_  lpBaseAddress
    wintypes.LPVOID,  # _Out_ lpBuffer
    SIZE_T,           # _In_  nSize
    PSIZE_T)          # _Out_ lpNumberOfBytesRead

kernel32.CloseHandle.argtypes = (wintypes.HANDLE,)
</code>```

function

```<code>def read_process_memory(pid, address, size, allow_partial=False):
    buf = (ctypes.c_char * size)()
    nread = SIZE_T()
    hProcess = kernel32.OpenProcess(PROCESS_VM_READ, False, pid)
    try:
        kernel32.ReadProcessMemory(hProcess, address, buf, size,
            ctypes.byref(nread))
    except WindowsError as e:
        if not allow_partial or e.winerror != ERROR_PARTIAL_COPY:
            raise
    finally:
        kernel32.CloseHandle(hProcess)
    return buf[:nread.value]
</code>```

example

```<code>if __name__ == '__main__':
    import os

    buf = ctypes.create_string_buffer(b'eggs and spam')
    pid = os.getpid()
    address = ctypes.addressof(buf)
    size = len(buf.value)

    value = read_process_memory(pid, address, size)
    assert value == buf.value
</code>```

Body:
I am trying to make Python get the value/data from an address such as 0x101BFFDC, which I found by using a cheat engine for a game. I've done much research and believe that I need to use ReadProcessMemory. However, I have tried several examples without success.

For example, I found the following code:

from ctypes import *
from ctypes.wintypes import *
import struct

OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory
CloseHandle = windll.kernel32.CloseHandle

PROCESS_ALL_ACCESS = 0x1F0FFF

pid = 10684 # pid of the game
address = 0x101BFFDC # I put the address here

buffer = c_char_p(b"The data goes here")
val = c_int()
bufferSize = len(buffer.value)
bytesRead = c_ulong(0)

processHandle = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
if ReadProcessMemory(processHandle, address, buffer, bufferSize, byref(bytesRead)):
    memmove(ctypes.byref(val), buffer, ctypes.sizeof(val))
    print("Success:" + str(val.value))
else:
    print("Failed.")

CloseHandle(processHandle)

I expect it to give me the value 56, which is what I get from the cheat engine. However, it just prints "Failed." every time.

How can I get the value right?

Body:
Here's a ctypes wrapper for WinAPI ReadProcessMemory. It takes the process ID, base address, and size in bytes to read. It returns the byte string read from the target process.

If allow_partial is false, the entire address range must be readable, else it fails with the Windows error code ERROR_PARTIAL_COPY. If allow_partial is true, the returned byte string may be less the number of requested bytes.

ctypes definitions

import ctypes
from ctypes import wintypes

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

ERROR_PARTIAL_COPY = 0x012B
PROCESS_VM_READ = 0x0010

SIZE_T = ctypes.c_size_t
PSIZE_T = ctypes.POINTER(SIZE_T)

def _check_zero(result, func, args):
    if not result:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

kernel32.OpenProcess.errcheck = _check_zero
kernel32.OpenProcess.restype = wintypes.HANDLE
kernel32.OpenProcess.argtypes = (
    wintypes.DWORD, # _In_ dwDesiredAccess
    wintypes.BOOL,  # _In_ bInheritHandle
    wintypes.DWORD) # _In_ dwProcessId

kernel32.ReadProcessMemory.errcheck = _check_zero
kernel32.ReadProcessMemory.argtypes = (
    wintypes.HANDLE,  # _In_  hProcess
    wintypes.LPCVOID, # _In_  lpBaseAddress
    wintypes.LPVOID,  # _Out_ lpBuffer
    SIZE_T,           # _In_  nSize
    PSIZE_T)          # _Out_ lpNumberOfBytesRead

kernel32.CloseHandle.argtypes = (wintypes.HANDLE,)

function

def read_process_memory(pid, address, size, allow_partial=False):
    buf = (ctypes.c_char * size)()
    nread = SIZE_T()
    hProcess = kernel32.OpenProcess(PROCESS_VM_READ, False, pid)
    try:
        kernel32.ReadProcessMemory(hProcess, address, buf, size,
            ctypes.byref(nread))
    except WindowsError as e:
        if not allow_partial or e.winerror != ERROR_PARTIAL_COPY:
            raise
    finally:
        kernel32.CloseHandle(hProcess)
    return buf[:nread.value]

example

if __name__ == '__main__':
    import os

    buf = ctypes.create_string_buffer(b'eggs and spam')
    pid = os.getpid()
    address = ctypes.addressof(buf)
    size = len(buf.value)

    value = read_process_memory(pid, address, size)
    assert value == buf.value


问:
Git: with uncommited work, how to make changes in another branch and come back?
My team is using a very simple Git workflow. Everybody develops in the same branch. I'd like to know which are the series of commands I should do when I'm in the middle of the work and need to fix a bug.

Here is my situation:

Unpushed commited changes in my local master branch

Uncommited modified files

need to fix a bug in origin/master branch

I don't have another branch attached to master

need to push just these files that fix the problem

go back to work

Se that I'm working in the same branch of my coworkers.

Some users pointed that git stash would solve it and so this is a duplicate question. I dispute it, since I didn't even know that this feature existed. The feature solves my problem, but I believe the question is valid since I ask it from another point of view.

答:
git stash might be what you're looking for.

Use git stash to temporarily store the changes you've made to tracked files. Go away and work on another branch. Then come back and do git stash pop.

The requires memory. You have to remember that you stashed stuff away.

Alternatively you can commit your work, go away work on another branch then come back and git reset HEAD^ to put the branch in the state it was before. So in effect putting a stash in context. So long as you don't push this work in progress that you committed you're OK.


问:
Ambiguity with pattern matching records
I learned from this question that it's possible to use pattern matching with records. However, I've noticed that I'm having trouble trying to match different types of records.

My goal in this example is to be able to distinguish between different records. I'm given a record that I'm not entirely sure which type it is, and I'm trying to figure it out using pattern matching.

Here's a simplified example:

```<code>module IceCream = struct
  type t = {
    temperature: float;
    toppings: string list;
  }
end

module Candy = struct
  type t = {
    flavour: string;
    colour: string;
    volume: int;
  }
end

(* Could be Candy or IceCream *)
let example =
  { Candy.
    flavour = "mint";
    colour = "green";
    volume = 10 }

let printFavoriteTreat treat = match treat with
  | { Candy.
      flavour = "mint";
      colour;
      volume } -> "It's Candy"
  | { IceCream.
      temperature;
      toppings } -> "It's IceCream"

let () = printFavoriteTreat example
</code>```

When I try to build this file, I get:

```<code>Error: The field IceCream.temperature belongs to the record type IceCream.t
       but a field was expected belonging to the record type Candy.t
</code>```

Is doing something like this possible?

答:
I'm given a record that I'm not entirely sure which type it is, and I'm trying to figure it out using pattern matching.

That is not possible. Types exist only at compile time, so checking what type it is at runtime is not possible.

In other words, in a valid program you can put a type annotation on every expression (in most cases you do not have to do that, though, thanks to type inference). If you cannot do that then you should design your program differently, such as using a sum type as others have suggested - in that case both values will have the same type (at compile time) but a different constructor (at run time).

Title: Ambiguity with pattern matching records

Body:
I learned from this question that it's possible to use pattern matching with records. However, I've noticed that I'm having trouble trying to match different types of records.

My goal in this example is to be able to distinguish between different records. I'm given a record that I'm not entirely sure which type it is, and I'm trying to figure it out using pattern matching.

Here's a simplified example:

module IceCream = struct
  type t = {
    temperature: float;
    toppings: string list;
  }
end

module Candy = struct
  type t = {
    flavour: string;
    colour: string;
    volume: int;
  }
end

(* Could be Candy or IceCream *)
let example =
  { Candy.
    flavour = "mint";
    colour = "green";
    volume = 10 }

let printFavoriteTreat treat = match treat with
  | { Candy.
      flavour = "mint";
      colour;
      volume } -> "It's Candy"
  | { IceCream.
      temperature;
      toppings } -> "It's IceCream"

let () = printFavoriteTreat example

When I try to build this file, I get:

Error: The field IceCream.temperature belongs to the record type IceCream.t
       but a field was expected belonging to the record type Candy.t

Is doing something like this possible?


问:
Web crawlers overloading site
We have a problem with a number of our sites where Yahoo, Google, Yandex, Bing Ahrefs and others all index the site at the same time which kills the website.

I've configured fail2ban to block the source IPs, but these are forever changing so not ideal.  I have also tried using robots.txt but this makes little difference.

We have tried putting the site behind cloudflare, but again this makes little difference and all we can do is block the source IPs.

What else can I do?

Currently we're monitoring the site with Nagios, which restarts nginx when the site becomes un-responsive, but this seems far from ideal.

Ubuntu server running nginx

Robots.txt file is here:-

```<code>User-agent: *
Disallow: /
</code>```

Posting here in case there is anything that I can get our developers to try.

Thanks

答:
Your robots.txt should have worked. And note that not all crawlers respect robots.txt.

robots.txt is case-sensitive, and it needs to be world-readable at www.yourdomain.com/robots.txt.

See what happens when you add Crawl-delay: 10.

Title: Web crawlers overloading site

Body:
We have a problem with a number of our sites where Yahoo, Google, Yandex, Bing Ahrefs and others all index the site at the same time which kills the website.

I've configured fail2ban to block the source IPs, but these are forever changing so not ideal.  I have also tried using robots.txt but this makes little difference.

We have tried putting the site behind cloudflare, but again this makes little difference and all we can do is block the source IPs.

What else can I do?

Currently we're monitoring the site with Nagios, which restarts nginx when the site becomes un-responsive, but this seems far from ideal.

Ubuntu server running nginx

Robots.txt file is here:-

User-agent: *
Disallow: /

Posting here in case there is anything that I can get our developers to try.

Thanks


问:
Ruby code looping infinitely
```<code>class Triplet
    def initialize(array,sum)
        @array = array.sort()
        @array_size = array.size()
        @sum = sum
        @result = []
    end

    def get_triplet
      @array[0..-3].each_with_index do |arr, ind|
        pointer_one = ind + 1
        pointer_two = @array_size - 1
        while (pointer_one < pointer_two)
          temp_sum = @array[pointer_one] + @array[pointer_two] + arr
          if(temp_sum == @sum)
            @result.push([@array[pointer_one], @array[pointer_two], arr])
          elsif temp_sum < @sum
            pointer_one = pointer_one +1
          else
            pointer_two = pointer_two -1
          end
        end
      end
    end

    def get_result
      @result.each do |res|
        puts res
      end
    end
end

puts "Enter the array of numbers"
array = gets.chomp
array = array.split(' ')
array_integer = array.map{|a| a.to_i}
puts array_integer
puts "Enter the sum"
sum = gets.chomp
puts sum
t1 = Triplet.new(array_integer,sum.to_i)
t1.get_triplet
t1.get_result
</code>```

<p>Can anyone suggest me the fix so that it doesn't loop infinitly. It is program to find triplet in array whose sum is @sum. Its  looping in get_triplet method. Initialize method sets the array,array size. get_triplet method should store all three number whose sum is @sum in result array. </p>

答:
Usually a tangle of code like this is a sign something's not right, and in this case the source of the problem is not knowing about the combination method. Here's a functionally equivalent solution:

```<code>def triplet(list, target)
  list.combination(3).find do |a,b,c|
    a + b + c == target
  end
end
</code>```

For example:

```<code>arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ]

p triplet(arr, 6)
# => [1, 2, 3]

p triplet(arr, 4)
# => nil

p triplet(arr, 10)
# => [1, 2, 7]
</code>```

The algorithm used in your code looks problematic, or at least implemented incorrectly, and is also strictly limited to triplets. This code is far more generic and uses a proven, tested algorithm, so it's probably better suited to solving your particular problem.

Title: Ruby code looping infinitely

Body:
class Triplet
    def initialize(array,sum)
        @array = array.sort()
        @array_size = array.size()
        @sum = sum
        @result = []
    end

    def get_triplet
      @array[0..-3].each_with_index do |arr, ind|
        pointer_one = ind + 1
        pointer_two = @array_size - 1
        while (pointer_one < pointer_two)
          temp_sum = @array[pointer_one] + @array[pointer_two] + arr
          if(temp_sum == @sum)
            @result.push([@array[pointer_one], @array[pointer_two], arr])
          elsif temp_sum < @sum
            pointer_one = pointer_one +1
          else
            pointer_two = pointer_two -1
          end
        end
      end
    end

    def get_result
      @result.each do |res|
        puts res
      end
    end
end

puts "Enter the array of numbers"
array = gets.chomp
array = array.split(' ')
array_integer = array.map{|a| a.to_i}
puts array_integer
puts "Enter the sum"
sum = gets.chomp
puts sum
t1 = Triplet.new(array_integer,sum.to_i)
t1.get_triplet
t1.get_result

Can anyone suggest me the fix so that it doesn't loop infinitly. It is program to find triplet in array whose sum is @sum. Its  looping in get_triplet method. Initialize method sets the array,array size. get_triplet method should store all three number whose sum is @sum in result array.

Body:
Usually a tangle of code like this is a sign something's not right, and in this case the source of the problem is not knowing about the combination method. Here's a functionally equivalent solution:

def triplet(list, target)
  list.combination(3).find do |a,b,c|
    a + b + c == target
  end
end

For example:

arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ]

p triplet(arr, 6)
# => [1, 2, 3]

p triplet(arr, 4)
# => nil

p triplet(arr, 10)
# => [1, 2, 7]

The algorithm used in your code looks problematic, or at least implemented incorrectly, and is also strictly limited to triplets. This code is far more generic and uses a proven, tested algorithm, so it's probably better suited to solving your particular problem.


问:
extract parts of URL string with regex
I have an object value/string that is a url. I need to extract the piece of the url that contains a unique identifier. How can this be done via regex?

Here is the example string:

```<code>http://images.example.com/examp/img/uuid/c49eccd1ddf1f4c341bf1d04140sdf7e261ae4014d422376cf9b293e6a8ad7/100/105/1.0
</code>```

I am trying to extract just what is after uuid/ and before /100

答:
You can do this without having to write a regex. Avoiding regex for simple tasks is usually preferred. Something like this might help:</p>

```<code>var str = window.location.href.split( "/uuid/" );
var yourAnswer = str[1].split( "/" );
yourAnswer = str[0];
</code>```

Title: extract parts of URL string with regex

Body:
I have an object value/string that is a url. I need to extract the piece of the url that contains a unique identifier. How can this be done via regex?

Here is the example string:

http://images.example.com/examp/img/uuid/c49eccd1ddf1f4c341bf1d04140sdf7e261ae4014d422376cf9b293e6a8ad7/100/105/1.0

I am trying to extract just what is after uuid/ and before /100

Body:
You can do this without having to write a regex. Avoiding regex for simple tasks is usually preferred. Something like this might help:

var str = window.location.href.split( "/uuid/" );
var yourAnswer = str[1].split( "/" );
yourAnswer = str[0];


答:
you could use </p>

```<code>var script = document.createElement("script");
script.type = "text/javascript";
script.id = "some_id";
script.src = 'http://haruair.com/externaljavascriptfile.js';
document.head.appendChild(script);
</code>```

<p>then call the function once finished </p>

Title: Loading external JavaScript file

Body:
you could use

var script = document.createElement("script");
script.type = "text/javascript";
script.id = "some_id";
script.src = 'http://haruair.com/externaljavascriptfile.js';
document.head.appendChild(script);

then call the function once finished


问:
kademlia closest good nodes won't intersect enough between two requests
working on bep44 implementation, i use the defined kademlia algorithm to find the closest good node given an hash id.

Using my program i do go run main.go -put "Hello World!" -kname mykey -salt foobar2 -b public and get the value stored over a hundred nodes (good).

Now, when i run it multiple consecutive times, the sets of ip which are written by the put requests poorly intersects.

It is a problem as when i try to do a get request, the set of ips queried does not intersect with the put set, so the value is not found.

In my tests i use the public dht bootstrap node

```<code>        "router.utorrent.com:6881",
        "router.bittorrent.com:6881",
        "dht.transmissionbt.com:6881",
</code>```

When i query the nodes, I select the 8 closest nodes (nodes := s.ClosestGoodNodes(8, msg.InfoHash())), which usually end up in a list of ~1K queries after a recursive traversal.

In my understanding, storing addresses of the info hash in the dht table is deterministic given the status of the table. As i m doing consecutive queries i expect the table to change, indeed, but not that much.

How does it happen the store nodes set does not intersect ?

答:
Since BEP44 is an extension it is only supported by a subset of the DHT nodes, which means the iterative lookup mechanism needs to take support into account when determining whether the set of closest nodes is stable and the lookup can be terminated.

If a node returns a token, v or seq field in in a get response then it is eligible for the closest-set of a read-only get.

If a node returns a token then it is eligible for the closest-set for a get that will be followed by put operation.

So your lookup may home in on a set of nodes in the keyspace that is closest to the target ID but not eligible for the operations in question. As long as you have candidates that are closer than the best known eligible contacts you have to continue searching. I call this perimeter widening, as it conceptually broadens the search area around the target.

Additionally you also need to take error responses or the absence of a response into account when performing put requests. You can either retry the node or try the next eligible node instead.

I have written down some additional constraints that one might want to put on the closest set in lookups for robustness and security reasons in the documentation of my own DHT implementation.

which usually end up in a list of ~1K queries after a recursive traversal.

This suggests something is wrong with your lookup algorithm. In my experience a lookup should only take somewhere between 60 and 200 udp requests to find its target if you're doing a lookup with concurrent requests, maybe even fewer when it is sequential.

Verbose logs of the terminal sets to eyeball how the lookups make progress and how much junk I am getting from peers have served me well.

In my tests i use the public dht bootstrap node

You should write your routing table to disk and reload it from there and only perform bootstrapping when none of the persisted nodes in your RT are reachable. Otherwise you are wasting the bootstrap nodes' resources and also waste time by having to re-populate your routing table first before performing any lookup.

Body:
working on bep44 implementation, i use the defined kademlia algorithm to find the closest good node given an hash id.

Using my program i do go run main.go -put "Hello World!" -kname mykey -salt foobar2 -b public and get the value stored over a hundred nodes (good).

Now, when i run it multiple consecutive times, the sets of ip which are written by the put requests poorly intersects.

It is a problem as when i try to do a get request, the set of ips queried does not intersect with the put set, so the value is not found.

In my tests i use the public dht bootstrap node

        "router.utorrent.com:6881",
        "router.bittorrent.com:6881",
        "dht.transmissionbt.com:6881",

When i query the nodes, I select the 8 closest nodes (nodes := s.ClosestGoodNodes(8, msg.InfoHash())), which usually end up in a list of ~1K queries after a recursive traversal.

In my understanding, storing addresses of the info hash in the dht table is deterministic given the status of the table. As i m doing consecutive queries i expect the table to change, indeed, but not that much.

How does it happen the store nodes set does not intersect ?


问:
Replace part of numpy 1D array with shorter array
I have a 1D numpy array containing some audio data. I'm doing some processing and want to replace certain parts of the data with white noise. The noise should, however, be shorter then the replaced part. Generating the noise is not a problem, but I'm wondering what the easiest way to replace the original data with the noise is. My first thought of doing data[10:110] = noise[0:10] does not work due to the obvious dimension mismatch.

What's the easiest way to replace a part of a numpy array with another part of different dimension?

edit:
The data is uncompressed PCM data that can be up to an hour long, taking up a few hundred MB of memory. I would like to avoid creating any additional copies in memory.

答:
not entirely familiar with numpy but can't you just break down the data array into pieces that are the same size as the noise array and set each data piece to the noise piece. for example:

```<code>data[10:20] = noise[0:10]
data[21:31] = noise[0:10]
</code>```

etc., etc.?

you could loop like this:

```<code>for x in range(10,100,10):
    data[x:10+x] = noise[0:10]
</code>```

UPDATE:

if you want to shorten the original data array, you could do this:

```<code>data = data[:10] + noise[:10]
</code>```

this will truncate the data array and add the the noise to the original array after the 10th location, you could then add the rest of the data array to the new array if you need it.

Body:
not entirely familiar with numpy but can't you just break down the data array into pieces that are the same size as the noise array and set each data piece to the noise piece. for example:

data[10:20] = noise[0:10]
data[21:31] = noise[0:10]

etc., etc.?

you could loop like this:

for x in range(10,100,10):
    data[x:10+x] = noise[0:10]

UPDATE:

if you want to shorten the original data array, you could do this:

data = data[:10] + noise[:10]

this will truncate the data array and add the the noise to the original array after the 10th location, you could then add the rest of the data array to the new array if you need it.


问:
Create controller with existing database and entity framework
hello I'm new in MVC and my project is CMS
I read some articles about mvc and I understand the code first concept.

My question is how to create controllers with existing Entity Framework? My colleagues here said that :

It should create an empty controller and create a new model for that controller but I don't know how.

Please help.

this are the codes generated when i added the controller with datacontext and model.

private SureSeatsDBEntities db = new SureSeatsDBEntities();

```<code>    //
    // GET: /Users/

    public ActionResult Index()
    {
        return View(db.SystemUsers.ToList());
    }

    //
    // GET: /Users/Details/5

    public ActionResult Details(int id = 0)
    {
        SystemUser systemuser = db.SystemUsers.Find(id);
        if (systemuser == null)
        {
            return HttpNotFound();
        }
        return View(systemuser);
    }

    //
    // GET: /Users/Create

    public ActionResult Create()
    {
        return View();
    }

    //
    // POST: /Users/Create

    [HttpPost]
    public ActionResult Create(SystemUser systemuser)
    {
        if (ModelState.IsValid)
        {
            db.SystemUsers.Add(systemuser);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(systemuser);
    }

    //
    // GET: /Users/Edit/5

    public ActionResult Edit(int id = 0)
    {
        SystemUser systemuser = db.SystemUsers.Find(id);
        if (systemuser == null)
        {
            return HttpNotFound();
        }
        return View(systemuser);
    }

    //
    // POST: /Users/Edit/5

    [HttpPost]
    public ActionResult Edit(SystemUser systemuser)
    {
        if (ModelState.IsValid)
        {
            db.Entry(systemuser).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(systemuser);
    }

    //
    // GET: /Users/Delete/5

    public ActionResult Delete(int id = 0)
    {
        SystemUser systemuser = db.SystemUsers.Find(id);
        if (systemuser == null)
        {
            return HttpNotFound();
        }
        return View(systemuser);
    }

    //
    // POST: /Users/Delete/5

    [HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(int id)
    {
        SystemUser systemuser = db.SystemUsers.Find(id);
        db.SystemUsers.Remove(systemuser);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }
</code>```

答:
You don't need to create the Models if you are using the Entity Framework as it will take care for you. And regarding the controller you do this by right clicking on the "Controllers" folder and navigating to

Add -> Controller

State your controller name and it will be created.

Body:
hello I'm new in MVC and my project is CMS
I read some articles about mvc and I understand the code first concept.

My question is how to create controllers with existing Entity Framework? My colleagues here said that :

It should create an empty controller and create a new model for that controller but I don't know how.

Please help.

this are the codes generated when i added the controller with datacontext and model.

private SureSeatsDBEntities db = new SureSeatsDBEntities();

    //
    // GET: /Users/

    public ActionResult Index()
    {
        return View(db.SystemUsers.ToList());
    }

    //
    // GET: /Users/Details/5

    public ActionResult Details(int id = 0)
    {
        SystemUser systemuser = db.SystemUsers.Find(id);
        if (systemuser == null)
        {
            return HttpNotFound();
        }
        return View(systemuser);
    }

    //
    // GET: /Users/Create

    public ActionResult Create()
    {
        return View();
    }

    //
    // POST: /Users/Create

    [HttpPost]
    public ActionResult Create(SystemUser systemuser)
    {
        if (ModelState.IsValid)
        {
            db.SystemUsers.Add(systemuser);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(systemuser);
    }

    //
    // GET: /Users/Edit/5

    public ActionResult Edit(int id = 0)
    {
        SystemUser systemuser = db.SystemUsers.Find(id);
        if (systemuser == null)
        {
            return HttpNotFound();
        }
        return View(systemuser);
    }

    //
    // POST: /Users/Edit/5

    [HttpPost]
    public ActionResult Edit(SystemUser systemuser)
    {
        if (ModelState.IsValid)
        {
            db.Entry(systemuser).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(systemuser);
    }

    //
    // GET: /Users/Delete/5

    public ActionResult Delete(int id = 0)
    {
        SystemUser systemuser = db.SystemUsers.Find(id);
        if (systemuser == null)
        {
            return HttpNotFound();
        }
        return View(systemuser);
    }

    //
    // POST: /Users/Delete/5

    [HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(int id)
    {
        SystemUser systemuser = db.SystemUsers.Find(id);
        db.SystemUsers.Remove(systemuser);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }


问:
Authorization header using Alamofire
I'm working with an API which puts an authorization key in the header, it works fine in Postman:

And it's my code:

```<code>let url = Requests.listCities(withLanguage: .en)
        let headers: HTTPHeaders = [ "Authorization": "pmJAdo5N26WW74kCEy6RRvIdCScFCbAtKc2o0FNy"]
        Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
            .validate(contentType: [MIMEType.JSON])
            .responseJSON {response in
                completion(response)
        }
</code>```

The response is:

```<code>SUCCESS: {
    error = Unauthorized;
    status = failed;
}
</code>```

Am I doing it wrong or is the Authorization omitted during the request?

This is the request debug:

```<code>$ curl -v \
    -H "Accept-Language: en;q=1.0, ar-US;q=0.9" \
    -H "Authorization: pmJAdo5N26WW74kCEy6RRvIdCScFCbAtKc2o0FNy" \
    -H "User-Agent: skinup/1.0 (appname; build:1; iOS 10.3.1) Alamofire/4.5.0" \
    -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5"
</code>```

答:
You can set the Alamofire's headers into an URLRequest. So you can do this:

```<code>    var urlRequest = URLRequest(url: URL(string: "your URL")!)
    urlRequest.httpMethod = HTTPMethod.get.rawValue
    urlRequest = try! URLEncoding.default.encode(urlRequest, with: nil)
    urlRequest.setValue("pmJAdo5N26WW74kCEy6RRvIdCScFCbAtKc2o0FNy", forHTTPHeaderField: "Authorization")

    Alamofire.request(urlRequest).responseJSON(completionHandler: {
        response in

        //code below
        completion(response)
    })
</code>```

Maybe It would solve your problem ;)

Title: Authorization header using Alamofire

Body:
I'm working with an API which puts an authorization key in the header, it works fine in Postman:

And it's my code:

let url = Requests.listCities(withLanguage: .en)
        let headers: HTTPHeaders = [ "Authorization": "pmJAdo5N26WW74kCEy6RRvIdCScFCbAtKc2o0FNy"]
        Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
            .validate(contentType: [MIMEType.JSON])
            .responseJSON {response in
                completion(response)
        }

The response is:

SUCCESS: {
    error = Unauthorized;
    status = failed;
}

Am I doing it wrong or is the Authorization omitted during the request?

This is the request debug:

$ curl -v \
    -H "Accept-Language: en;q=1.0, ar-US;q=0.9" \
    -H "Authorization: pmJAdo5N26WW74kCEy6RRvIdCScFCbAtKc2o0FNy" \
    -H "User-Agent: skinup/1.0 (appname; build:1; iOS 10.3.1) Alamofire/4.5.0" \
    -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5"

Body:
You can set the Alamofire's headers into an URLRequest. So you can do this:

    var urlRequest = URLRequest(url: URL(string: "your URL")!)
    urlRequest.httpMethod = HTTPMethod.get.rawValue
    urlRequest = try! URLEncoding.default.encode(urlRequest, with: nil)
    urlRequest.setValue("pmJAdo5N26WW74kCEy6RRvIdCScFCbAtKc2o0FNy", forHTTPHeaderField: "Authorization")

    Alamofire.request(urlRequest).responseJSON(completionHandler: {
        response in

        //code below
        completion(response)
    })

Maybe It would solve your problem ;)


问:
Windows Cmd - How to delete all but a given file type
I am looking for something like this:

```<code>  Process.Start("cmd.exe", "/C del path\*.(filetypetobedeleted)");
</code>```

but instead I want to delete all but one type of file type (.txt). This includes folders in the path, so I want everything in the path to be deleted but .txt files.

答:
Something like this should do the trick:

```<code>// Set as read-only
Process.Start("cmd.exe", "/C attrib +r " + path + "\\*." + ext);

// Del will skip read-only
Process.Start("cmd.exe", "/C del " + path + "/q *");

// Rm folders recursively
Process.Start("cmd.exe", "/C for /d %i in (" + path + "\\*) do rd /s /q \"%i\"");

// Remove read-only
Process.Start("cmd.exe", "/C attrib -r " + path + "\\*." + ext);
</code>```

You probably want to give it a second to do its thing. As mentioned by @TheLethalCoder, you can proc.WaitForExit()if using a single Process instance.

Edit: This gets ugly very quickly. You should be using.NET for this. Or even Power-Shell as explained by @PanagiotisKanavos.

Body:
I am looking for something like this:

  Process.Start("cmd.exe", "/C del path\*.(filetypetobedeleted)");

but instead I want to delete all but one type of file type (.txt). This includes folders in the path, so I want everything in the path to be deleted but .txt files.

Body:
Something like this should do the trick:

// Set as read-only
Process.Start("cmd.exe", "/C attrib +r " + path + "\\*." + ext);

// Del will skip read-only
Process.Start("cmd.exe", "/C del " + path + "/q *");

// Rm folders recursively
Process.Start("cmd.exe", "/C for /d %i in (" + path + "\\*) do rd /s /q \"%i\"");

// Remove read-only
Process.Start("cmd.exe", "/C attrib -r " + path + "\\*." + ext);

You probably want to give it a second to do its thing. As mentioned by @TheLethalCoder, you can proc.WaitForExit()if using a single Process instance.

Edit: This gets ugly very quickly. You should be using.NET for this. Or even Power-Shell as explained by @PanagiotisKanavos.


问:
Is this x in local scope of inner function?
Consider the following code, I expected the output to be 2 since the x to be printed is a local variable in the scope of inner function. However, it printed 2 instead. I don't understand why that is the case. Any explanation and/or comment is appreciated.

```<code>def outer():
    x = 1
    def inner():
        x = 1
        x += 1
        print x
    return x
</code>```

答:
There are two separate x variables here: the outer function has an x variable and the inner function has its own x variable.

From the moment there is an assignment to a variable somewhere in a function, the variable has a local scope.

So when you call outer(), you will return 1. The x in the inner function is a different one, and furthermore inner() is never called. As a result, the (local) x is not printed.

If you thus would have written:

```<code>def outer():
    x = 3
    def inner():
        x = 1
        x += 1
        print x
    return x
</code>```

Then calling outer() will return 3. Even if you would have called inner() in the outer() function, it would not make any difference. Since the x in the inner() function is another one than the one in the outer() function (there is a local scope defined in inner). Although it would mean that you print 2, you will return 3.

Body:
Consider the following code, I expected the output to be 2 since the x to be printed is a local variable in the scope of inner function. However, it printed 2 instead. I don't understand why that is the case. Any explanation and/or comment is appreciated.

def outer():
    x = 1
    def inner():
        x = 1
        x += 1
        print x
    return x

Body:
There are two separate x variables here: the outer function has an x variable and the inner function has its own x variable.

From the moment there is an assignment to a variable somewhere in a function, the variable has a local scope.

So when you call outer(), you will return 1. The x in the inner function is a different one, and furthermore inner() is never called. As a result, the (local) x is not printed.

If you thus would have written:

def outer():
    x = 3
    def inner():
        x = 1
        x += 1
        print x
    return x

Then calling outer() will return 3. Even if you would have called inner() in the outer() function, it would not make any difference. Since the x in the inner() function is another one than the one in the outer() function (there is a local scope defined in inner). Although it would mean that you print 2, you will return 3.


答:
if the unique ID is /c49eccd1ddf1f4c341bf1d04140sdf7e261ae4014d422376cf9b293e6a8ad7/

you can use this regex '[a-z0-9]{62}' which would mean, a 62 character interval of non-cap letters and numbers.

if you know the length is in between two values, lets say 50-70, you could type it like this: '[a-z0-9]{50,70}'

definetly @jonas-w answer is way better and does not require regexes.

Title: extract parts of URL string with regex


问:
Import C dll function in python
Which data type should be used in this stringUpcase function in my DLL file

```<code>void __cdecl stringUpcase(char IN_str[], char OUT_str[], int32_t len);
</code>```

I am trying ctype.c_char_p in Python 3.6 and This function should return the uppercase string "HELO" in OUT_str variable.

```<code>dl = ctypes.cdll.LoadLibrary("path/of/dll/file.dll")

IN_str = 'helo'
OUT_str = ''
IN_len = len(IN_str)

dl.stringUpcase.restype = ctypes.c_void_p
dl.stringUpcase.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int32]

dl.stringUpcase(IN_str, OUT_str, IN_len);
</code>```

Console error output is

```<code> line 21, in <module>
    dl.stringUpcase(IN_str, OUT_str, IN_len);
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type
</code>```

Thank you for any help you can provide.

答:
You are trying to pass python string as an argument of type c_char_p. Python3 unlike python2 is pretty strict about typing in ctypes.

The working sample would look like this.

import ctypes

ins = ctypes.c_char_p(b'helo')
lens = len(ins.value)
outs = ctypes.create_string_buffer(lens+1)
lib = ctypes.cdll.LoadLibrary("./upper.so")

lib.stringUpcase.restype = None
lib.stringUpcase.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int32]

lib.stringUpcase(ins, outs, lens)

print(outs.value)
```

Pay attention to the fact that c_char_p points to a zero-terminated string, so len argument is redundant here. Moreover to construct c_char_p you need to pass bytes object or and integer address rather than just a string, to be able to use string as an argument you need to use c_wchar_p type and wchar_t* in your library respectively.

One more thing to pay attention to is the fact that your C function does not allocate memory so you need for outs to be large enough to contain the result.

Title: Import C dll function in python

Body:
Which data type should be used in this stringUpcase function in my DLL file

void __cdecl stringUpcase(char IN_str[], char OUT_str[], int32_t len);

I am trying ctype.c_char_p in Python 3.6 and This function should return the uppercase string "HELO" in OUT_str variable.

dl = ctypes.cdll.LoadLibrary("path/of/dll/file.dll")

IN_str = 'helo'
OUT_str = ''
IN_len = len(IN_str)

dl.stringUpcase.restype = ctypes.c_void_p
dl.stringUpcase.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int32]

dl.stringUpcase(IN_str, OUT_str, IN_len);

Console error output is

 line 21, in <module>
    dl.stringUpcase(IN_str, OUT_str, IN_len);
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type

Thank you for any help you can provide.

Body:
You are trying to pass python string as an argument of type c_char_p. Python3 unlike python2 is pretty strict about typing in ctypes.

The working sample would look like this.

import ctypes

ins = ctypes.c_char_p(b'helo')
lens = len(ins.value)
outs = ctypes.create_string_buffer(lens+1)
lib = ctypes.cdll.LoadLibrary("./upper.so")

lib.stringUpcase.restype = None
lib.stringUpcase.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int32]

lib.stringUpcase(ins, outs, lens)

print(outs.value)

Pay attention to the fact that c_char_p points to a zero-terminated string, so len argument is redundant here. Moreover to construct c_char_p you need to pass bytes object or and integer address rather than just a string, to be able to use string as an argument you need to use c_wchar_p type and wchar_t* in your library respectively.

One more thing to pay attention to is the fact that your C function does not allocate memory so you need for outs to be large enough to contain the result.


问:
double.IsNan is not defined? (upgrade from 1.9.7.8 -> 2.0)
Trying out VS 2010, but still want to target .NET 3.5.  Have all my C# projects set with:

```<code><PropertyGroup> <LangVersion>3</LangVersion> </PropertyGroup>
</code>```

And seems to be working fine.  The F# is acting funny though.. I can't use the double.IsNaN method.

```<code>let foo = double.IsNaN(bar)

The field, constructor, or member 'IsNaN' is not defined.
</code>```

Similarly, String.Format is broke too:

```<code>The field, constructor, or member 'Format' is not defined.
</code>```

I must be missing something here.

答:
Explicitly stated "open System" and capitalized double (Double).

Not sure why it was fine before..

Body:
Trying out VS 2010, but still want to target .NET 3.5.  Have all my C# projects set with:

<PropertyGroup> <LangVersion>3</LangVersion> </PropertyGroup>

And seems to be working fine.  The F# is acting funny though.. I can't use the double.IsNaN method.

let foo = double.IsNaN(bar)

The field, constructor, or member 'IsNaN' is not defined.

Similarly, String.Format is broke too:

The field, constructor, or member 'Format' is not defined.

I must be missing something here.


问:
What is the most customisable apex-region type/ plug-in based on a table?
I'd like to display the contents of a database table in a more interesting manner than just a table; different positioning, fonts, sizes, colours etc.

Is there a region type or plugin that can achieve that?

I tried the cards view but I it's still very limited (for example a minimum of 2 cards per row when I only need 1) Or maybe I should deploy it as a classic report and then use javascript to rearrange everything? edit: I also considered rendering the page with pl/sql and htp, but that seems overly complicated...

As I'm new to APEX, any input would be much appreciated!

答: You could do it as a classic report and change the template under the attributes to something else.


问:
Sum two input values in realtime
I want to sum two different inputs in a third realtime variable. I will explain better what I want:

1 variable : 100 (input)

2 variable : 150 (input)

sum : 250 (not input)

How can I do this?

答:
Here is also a version in plain javascript: </p>

```<code>    <!doctype html>
<html>
<head>
</head>
<body>

<input type="text" id="val1">
<input type="text" id="val2">
<input type="button" value="Calculate" onclick="calculate();">
<script>

function calculate(){

var val1 = document.getElementById('val1').value;
var val2 = document.getElementById('val2').value;
var res = (parseFloat(val1)+parseFloat(val2))

alert(res);

}

</script>
</code>```

<p>
</p>

Title: Sum two input values in realtime

Body:
Here is also a version in plain javascript:

    <!doctype html>
<html>
<head>
</head>
<body>

<input type="text" id="val1">
<input type="text" id="val2">
<input type="button" value="Calculate" onclick="calculate();">
<script>

function calculate(){

var val1 = document.getElementById('val1').value;
var val2 = document.getElementById('val2').value;
var res = (parseFloat(val1)+parseFloat(val2))

alert(res);

}

</script>


问:
Counter value is not working properly after first attempt in bootstrap modal
I am having bootstrap modal in which I have made it close automatically after 7 seconds and which is working fine till here.

My problem is I have shown counter seconds also under modal and which is working fine in the first attempt. But after the first attempt instead of starting from 0 seconds it starts from any random number. I don't know what I am missing in it.

$(function() {
  $('.thank_you_modal').on('show.bs.modal', function() {

    var myModal = $(this);
    clearTimeout(myModal.data('hideInterval'));
    myModal.data('hideInterval', setTimeout(function() {
      myModal.modal('hide');
    }, 7000));

    var sec = 0;

    function pad(val) {
      return val > 9 ? val : "0" + val;
    }
    var timer = setInterval(function() {
      document.getElementById("seconds").innerHTML = pad(++sec % 60);
      document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
    }, 1000);

    setTimeout(function() {
      clearInterval(timer);
    }, 7000);

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#custom_modal .modal-content+span {
  color: #fff;
  text-align: center;
  display: block;
  font-size: 12px;
  margin-top: 12px;
}</code>```

Click me

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×</button>

Thank You

    This message will close in 00 seconds

```

Working Code in Codepen

答:
This code is working for me in the codepen you provided !

```<code>$(function(){
    $('.thank_you_modal').on('show.bs.modal', function(){

        var myModal = $(this);
        clearTimeout(myModal.data('hideInterval'));
        myModal.data('hideInterval', setTimeout(function(){
            myModal.modal('hide');
        }, 7000));

 var sec = 7;

function pad(val) {
    return val > 2 ? val : "0" + val;
}
var timer = setInterval(function () {
    document.getElementById("seconds").innerHTML = pad(--sec % 60);
    document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);

setTimeout(function () {
    clearInterval(timer);
    sec = 7;
}, 7000);

    });
});
</code>```

The problem is that you forget to reinitialize your "sec" to 7 (for countdown effect) !

Body:
I am having bootstrap modal in which I have made it close automatically after 7 seconds and which is working fine till here.

My problem is I have shown counter seconds also under modal and which is working fine in the first attempt. But after the first attempt instead of starting from 0 seconds it starts from any random number. I don't know what I am missing in it.

$(function() {
  $('.thank_you_modal').on('show.bs.modal', function() {

    var myModal = $(this);
    clearTimeout(myModal.data('hideInterval'));
    myModal.data('hideInterval', setTimeout(function() {
      myModal.modal('hide');
    }, 7000));

    var sec = 0;

    function pad(val) {
      return val > 9 ? val : "0" + val;
    }
    var timer = setInterval(function() {
      document.getElementById("seconds").innerHTML = pad(++sec % 60);
      document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
    }, 1000);

    setTimeout(function() {
      clearInterval(timer);
    }, 7000);

  });
});

#custom_modal .modal-content+span {
  color: #fff;
  text-align: center;
  display: block;
  font-size: 12px;
  margin-top: 12px;
}

Click me

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×</button>

Thank You

    This message will close in 00 seconds

Working Code in Codepen

Body:
This code is working for me in the codepen you provided !

$(function(){
    $('.thank_you_modal').on('show.bs.modal', function(){

        var myModal = $(this);
        clearTimeout(myModal.data('hideInterval'));
        myModal.data('hideInterval', setTimeout(function(){
            myModal.modal('hide');
        }, 7000));

 var sec = 7;

function pad(val) {
    return val > 2 ? val : "0" + val;
}
var timer = setInterval(function () {
    document.getElementById("seconds").innerHTML = pad(--sec % 60);
    document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);

setTimeout(function () {
    clearInterval(timer);
    sec = 7;
}, 7000);

    });
});

The problem is that you forget to reinitialize your "sec" to 7 (for countdown effect) !


问:
Roxy File Man Loading error
I am using Roxy Fileman in ckeditor to add and manage images. This was working perfectly in my local Xampp server. When i use it in live server, after click on browse, E_LoadingAjax php/dirtree.php error alert is shown.

can anyone know how to solve this?.

答:
For me, the problem was that the .htaccess file had a RewriteRule that was blocking http access to required files.

The Roxy FAQ says that you should be able to load dirtree.php in a browser window.  In my case, that file was throwing a 403 until I removed/updated the htaccess RewriteRule.

Title: Roxy File Man Loading error


问:
How to convert a column filled with integer to text format - VBA - Excel
I'm trying to convert all data in column B , which currently are integers ex. 26, to text format, ex "26". I have tried the following:

```<code>Dim index As Long

index = 2

Do While index_5 <> NewResizeRange

   Worksheets("Source").Cells(index, "B").Value = CStr(Worksheets("Source").Cells(index, "B").Value)

   index = index + 1

Loop
</code>```

Which turned to be extremely slow and ineffective.

I also tried:

```<code>Sub Macro8()

   Columns("E:E").Select
   Selection.TextToColumns Destination:=Range("Table1[[#Headers],[Column5]]"), _
    DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter _
    :=False, Tab:=True, Semicolon:=False, Comma:=False, Space:=False, _
    Other:=False, FieldInfo:=Array(1, 2), TrailingMinusNumbers:=True
End Sub
</code>```

Problem is that when the data comes from another worksheet and the cell is refering to said worksheet it is only displaying the location of the data in the cell.

Any ideas?

答:
is this what you looking for?

```<code>Range("B1:B288889").NumberFormat = "@"
</code>```

Cheers

Elmnas

Body:
I'm trying to convert all data in column B , which currently are integers ex. 26, to text format, ex "26". I have tried the following:

Dim index As Long

index = 2

Do While index_5 <> NewResizeRange

   Worksheets("Source").Cells(index, "B").Value = CStr(Worksheets("Source").Cells(index, "B").Value)

   index = index + 1

Loop

Which turned to be extremely slow and ineffective.

I also tried:

Sub Macro8()

   Columns("E:E").Select
   Selection.TextToColumns Destination:=Range("Table1[[#Headers],[Column5]]"), _
    DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter _
    :=False, Tab:=True, Semicolon:=False, Comma:=False, Space:=False, _
    Other:=False, FieldInfo:=Array(1, 2), TrailingMinusNumbers:=True
End Sub

Problem is that when the data comes from another worksheet and the cell is refering to said worksheet it is only displaying the location of the data in the cell.

Any ideas?

Body:
is this what you looking for?

Range("B1:B288889").NumberFormat = "@"

Cheers

Elmnas


问:
Export nested BigQuery data to cloud storage
I am trying to export bigquery data to google cloud storage bucket via the API. I adapted a code snippet from here
https://cloud.google.com/bigquery/docs/exporting-data

```<code>Job job = table.extract(format, gcsUrl);
// Wait for the job to complete
try {
  Job completedJob = job.waitFor(WaitForOption.checkEvery(1,
TimeUnit.SECONDS),
      WaitForOption.timeout(3, TimeUnit.MINUTES));
  if (completedJob != null && completedJob.getStatus().getError() == null) {
    // Job completed successfully
  } else {
    // Handle error case
       System.out.println(completedJob.getStatus().getError());
  }
} catch (InterruptedException | TimeoutException e) {
  // Handle interrupted wait

}
</code>```

I have exchanged format with "JSON" since my data is nested and can't be exported to CSV and the gcsUrl with "gs://mybucket/export_*.json".
 But the error messages tells me the following problem:

```<code>transfer not working  BigQueryError{reason=invalid, location=null, message=Operation cannot be performed on a nested schema. Field: totals}
</code>```

Any advice what to do? JSON should be able to handle a nested format...

答: Referring to the destinationFormat option, you should set "NEWLINE_DELIMITED_JSON" for the format variable in order to export as JSON.

Body:
I am trying to export bigquery data to google cloud storage bucket via the API. I adapted a code snippet from here
https://cloud.google.com/bigquery/docs/exporting-data

Job job = table.extract(format, gcsUrl);
// Wait for the job to complete
try {
  Job completedJob = job.waitFor(WaitForOption.checkEvery(1,
TimeUnit.SECONDS),
      WaitForOption.timeout(3, TimeUnit.MINUTES));
  if (completedJob != null && completedJob.getStatus().getError() == null) {
    // Job completed successfully
  } else {
    // Handle error case
       System.out.println(completedJob.getStatus().getError());
  }
} catch (InterruptedException | TimeoutException e) {
  // Handle interrupted wait

}

I have exchanged format with "JSON" since my data is nested and can't be exported to CSV and the gcsUrl with "gs://mybucket/export_*.json".
 But the error messages tells me the following problem:

transfer not working  BigQueryError{reason=invalid, location=null, message=Operation cannot be performed on a nested schema. Field: totals}

Any advice what to do? JSON should be able to handle a nested format...


问:
Vimeo PHP API - Make Authenticated Request
I'm using the Vimeo API here:
https://github.com/vimeo/vimeo.php

I've included it like this:

```<code> // include the autoload file from the vimeo php library that was downloaded
include __DIR__ . '/vimeo/autoload.php';

// The client id and client secret needed to use the vimeo API
$clientId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

// when getting an auth token we need to provide the scope
// all possible scopes can be found here https://developer.vimeo.com/api/authentication#supported-scopes
$scope = array('public', 'private');

// initialize the vimeo library
$lib = new \Vimeo\Vimeo($clientId, $clientSecret);

// request an auth token (needed for all requests to the Vimeo API)
$token = $lib->clientCredentials($scope);

// redirect_uri must be provided, and must match your configured uri
$token = $lib->accessToken(code, redirect_uri);

// use the token
$lib->setToken($token['body']['access_token']);
</code>```

Then I try to get the video thumb url:

```<code>$vimeo_response = $lib->request('/videos/218234161/pictures', 'GET');
</code>```

This just returns a null value.

I'm not sure what else to try at this point.

答:
I ended up getting it working by generating an access token here:
https://developer.vimeo.com/apps

Once I had the token along with client id and secret, this was is code:

```<code>    // include the autoload file from the vimeo php library that was
    include __DIR__ . '/vimeo/autoload.php';
    use Vimeo\Vimeo;

    function get_vimeo_thumb($vimeo_video_id){

    // The client id and client secret needed to use the vimeo API
    $clientId = "XXXXXXXXXXXXXXXXXXXXXXX";
    $clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXX";
    $access_token = "XXXXXXXXXXXXXXXXXXXXXXXXX";

    //// initialize the vimeo library
    $vimeo = new Vimeo($clientId, $clientSecret);

    // Set access token
    $vimeo->setToken($access_token);

    $thumb = $vimeo->request("/videos/" . $vimeo_video_id . "/pictures/");
    return $thumb['body']['data'][0]['sizes'][2]['link'];

   }
</code>```

Body:
I'm using the Vimeo API here:
https://github.com/vimeo/vimeo.php

I've included it like this:

 // include the autoload file from the vimeo php library that was downloaded
include __DIR__ . '/vimeo/autoload.php';

// The client id and client secret needed to use the vimeo API
$clientId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

// when getting an auth token we need to provide the scope
// all possible scopes can be found here https://developer.vimeo.com/api/authentication#supported-scopes
$scope = array('public', 'private');

// initialize the vimeo library
$lib = new \Vimeo\Vimeo($clientId, $clientSecret);

// request an auth token (needed for all requests to the Vimeo API)
$token = $lib->clientCredentials($scope);

// redirect_uri must be provided, and must match your configured uri
$token = $lib->accessToken(code, redirect_uri);

// use the token
$lib->setToken($token['body']['access_token']);

Then I try to get the video thumb url:

$vimeo_response = $lib->request('/videos/218234161/pictures', 'GET');

This just returns a null value.

I'm not sure what else to try at this point.

Body:
I ended up getting it working by generating an access token here:
https://developer.vimeo.com/apps

Once I had the token along with client id and secret, this was is code:

    // include the autoload file from the vimeo php library that was
    include __DIR__ . '/vimeo/autoload.php';
    use Vimeo\Vimeo;

    function get_vimeo_thumb($vimeo_video_id){

    // The client id and client secret needed to use the vimeo API
    $clientId = "XXXXXXXXXXXXXXXXXXXXXXX";
    $clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXX";
    $access_token = "XXXXXXXXXXXXXXXXXXXXXXXXX";

    //// initialize the vimeo library
    $vimeo = new Vimeo($clientId, $clientSecret);

    // Set access token
    $vimeo->setToken($access_token);

    $thumb = $vimeo->request("/videos/" . $vimeo_video_id . "/pictures/");
    return $thumb['body']['data'][0]['sizes'][2]['link'];

   }


问:
how to build multiple visual studio targets in team city
I'm using the "visual studio (.sln)" builder in teamcity 6.0, I would like to compile both the "debug" and "release" configuration targets. can I do it using a single builder so I dont repeat myself?</p>

答: You could create a new target in csproj that then calls to Release and Debug</p>


问:
What exactly constructors do?
Yesterday I was reading PHP classes and suddenly something got weird to me. And that was about constructors in C# and PHP.

My question is what is constructor? Isn't it a special methods, used when instantiating a class that can does something like a method and take necessary resources for class like Memory and etc? And if it is, for example when we have a parent class named A which we derive another class named B and create an instance of B and call the B  constructor and send some arguments to its parent (A) use :base(args.) (in C#) and use parent::__construct(args) (in PHP) , so is it goes and call the parent constructor , we don't want to exactly take resources for the parent but we just call the parent constructor which do it's for us. What happen exactly here?

I guess in this case simply just called it like a function! :\ i don't know i made my self clear or not ... Ask me if there is any Ambiguity, and Thanks ;)

UPDATED
Thank by giving me the negative vote by the way ...
look at this link :
Microsoft Docs
as far i read here it's something more than a simple function which hold a block of codes.(but with differences which you said , no return value and etc.)
if it is just a function which called when an instance get created so why if we make it private then we can not make any instance of it anymore?
why when we wanted to create a class add a () at the end of the class name?and when we want to pass any args to constructor use those () to send ?
[Person new_person = new Person();]
if you think also this a question which doesn't show any effort , vote negative again :D

答:
A constructor is basically just a function. The difference between a normal function and a constructor is, that a Constructor

Doesn't have a return value (not even void)

Is named like the class itself (or has a predefined special name)

Is classified as a mandatory function that has to be executed before the object is in an usable state

Can not be called like other functions

The constructor will be called automatically when creating a new instance of the object.

Update:

To understand why you can't create a new instance of something with a private constructor (from outside) look at it as a normal function for a moment.

If you want to call new ClassWithPrivateConstructor() from outside of said class it will not work because the you do not have access to the constructor.

You may now think that a private constructor is useless. But that's not the case. There are valid cases. Eg. singleton Objects.

And for the () think of a constructor as a normal function again. You want to call the constructor. Maybe even with arguments. That's why you need the () when creating a new instance of an object.

Title: What exactly constructors do?


问:
Balanced corpus for Naive Bayes Classifier
I'm working with sentiment analysis using NB classifier. I've found some information (blogs, tutorials etc) that training corpus should be balanced:

33.3% Positive;

33.3% Neutral

33.3% Negative

My question is:

Why corspus should be balanced? The Bayes theorem is based on propability of reason/case. So for training purpose isn't it important that in real world for example negative tweets are only 10% not 33.3%?

答:
In my opinion the best dataset for training purposes if a sample of the real world data that your classifier will be used with.

This is true for all classifiers (but some of them are indeed not suitable to unbalanced training sets in which cases you don't really have a choice to skew the distribution), but particularly for probabilistic classifiers such as Naive Bayes. So the best sample should reflect the natural class distribution.

Note that this is important not only for the class priors estimates. Naive Bayes will calculate for each feature the likelihood of predicting the class given the feature. If your bayesian classifier is built specifically to classify texts, it will use global document frequency measures (the number of times a given word occurs in the dataset, across all categories). If the number of documents per category in the training set doesn't reflect their natural distribution, the global term frequency of terms usually seen in unfrequent categories will be overestimated, and that of frequent categories underestimated. Thus not only the prior class probability will be incorrect, but also all the P(category=c|term=t) estimates.


问:
How to remember user choices in react router?
I am using react router to build a single page app.Now, everything is fine, except remembering the previous status. I mean: each time when user chooses one option in a select dom, then click a link component to jump to another route path; then, if this user clicks back button from browser to go back to the previous page, he can not see his previous choice, everything lost!</p>

答:
The desired behavior you are talking about is about saving the State of the Component. Even though the router renders the desired Component, it does not save the State of that Component.
However, you can pass in a desired State via URL Parameters, but that doesn't like a solution for you due to what exactly you are trying to achieve.

Passing data in through the URL to achieve the state may sound like a good idea, but this won't work due to the URL having to be updated as the User selects different options, and this will trigger new rendering. This will happen because you are currently on that route.

```<code>//the route path can be defined like this:
localhost:123/#/userselection/:selectedid

When you navigate it will look something like this
localhost:123/#/userselection/1
localhost:123/#/userselection/2
localhost:123/#/userselection/3
etc.

//Now if you are on
localhost:123/#/userselection/2

and the User changes to selectionid 3, you will have to trigger a render
which is not usually desired behaviour
</code>```

An idea may be to have some sort of ComponentStateService that is declared at a root level of your application. Use this Service to set and read desired state. So when the User selects something, have an Object with the Component Name, and its stateData.

```<code>export default class ComponentStateService{
    _stateData = {};

    constructor(defaultState = null){
        if (defaultState){
            this._stateData = defaultState;
        }
    }

    getComponentStateData(componentName){
        if (this._stateData){
            return this._stateData[componentName];
        }

    }

    setComponentStateData(componentName, stateData){
        this._stateData[componentName] = stateData;
    }
}
</code>```

Then initialize it something like this at a high level:

```<code>import ComponentStateService from './componentStateService';

var componentState = new ComponentStateService(//default state passed in here);
export default componentState;
</code>```

Then to use it, import it to each component

```<code>import componentState from '../index';

// call this to set the state
componentState.setComponentStateData("component1", {});
// and retrieve state
let savedState = componentState.getComponentStateData("component1");
</code>```

Then you retrieve or update as necessary. You can make use of the LifeCycle Hooks that react has in order to read and set the data before the Comopnent is Rendered. Also you will need to ensure that you are correctly updating the data for the state upon User changing their selection.

As you can see though, the major flaw is you cannot share your link and expect someone else to see what you see, since it will persist in a Users Browser Session.

You can create a base class that imports this, so you don't have to import it every time.

You can also dump the entire state to local storage so it persists beyond a session, and load it up on app start

Body:
The desired behavior you are talking about is about saving the State of the Component. Even though the router renders the desired Component, it does not save the State of that Component.
However, you can pass in a desired State via URL Parameters, but that doesn't like a solution for you due to what exactly you are trying to achieve.

Passing data in through the URL to achieve the state may sound like a good idea, but this won't work due to the URL having to be updated as the User selects different options, and this will trigger new rendering. This will happen because you are currently on that route.

//the route path can be defined like this:
localhost:123/#/userselection/:selectedid

When you navigate it will look something like this
localhost:123/#/userselection/1
localhost:123/#/userselection/2
localhost:123/#/userselection/3
etc.

//Now if you are on
localhost:123/#/userselection/2

and the User changes to selectionid 3, you will have to trigger a render
which is not usually desired behaviour

An idea may be to have some sort of ComponentStateService that is declared at a root level of your application. Use this Service to set and read desired state. So when the User selects something, have an Object with the Component Name, and its stateData.

export default class ComponentStateService{
    _stateData = {};

    constructor(defaultState = null){
        if (defaultState){
            this._stateData = defaultState;
        }
    }

    getComponentStateData(componentName){
        if (this._stateData){
            return this._stateData[componentName];
        }

    }

    setComponentStateData(componentName, stateData){
        this._stateData[componentName] = stateData;
    }
}

Then initialize it something like this at a high level:

import ComponentStateService from './componentStateService';

var componentState = new ComponentStateService(//default state passed in here);
export default componentState;

Then to use it, import it to each component

import componentState from '../index';

// call this to set the state
componentState.setComponentStateData("component1", {});
// and retrieve state
let savedState = componentState.getComponentStateData("component1");

Then you retrieve or update as necessary. You can make use of the LifeCycle Hooks that react has in order to read and set the data before the Comopnent is Rendered. Also you will need to ensure that you are correctly updating the data for the state upon User changing their selection.

As you can see though, the major flaw is you cannot share your link and expect someone else to see what you see, since it will persist in a Users Browser Session.

You can create a base class that imports this, so you don't have to import it every time.

You can also dump the entire state to local storage so it persists beyond a session, and load it up on app start


问:
Datatables with ajax and js variable in data doesn't propagate
I'm using datatables and data is loaded with AJAX with custom data
but on custom data refrence variable is changed and ajax is reloaded the custom data value is not changed

```<code> var range=1;
var DataTable=$('#tableid_table').DataTable( {
    "lengthMenu": [[10,25,50,100, -1], [10,25,50,100, "All"]],
    "processing": true,
    "serverSide": true,
    "ajax":{ url:'phpqueryfile.php',type: 'POST',dataType: "json","data": {
        "range": select
    }}
} );

$('.range').click(function () {
    alert($(this).attr("value"));
    select=$(this).attr("value");
    DataTable.ajax.reload();

})
</code>```

when range click is called and range is changed to any other value, ajax is reloaded with range=1

Edit: i managed to send data after changing

```<code>var select=1;
var DataTable=$('#mygradedcalls_table').DataTable( {

    "lengthMenu": [[10,25,50,100, -1], [10,25,50,100, "All"]],
    "processing": true,
    "serverSide": true,
    "ajax":{ url:'../Queries_PHP/grad/getAllMyGradedCalls.php',type: 'POST',dataType: "json",data:function (range) {
        Object.assign(range, select);
        return range;
    }
    }
} );

$('.range').click(function () {
    select=$(this).attr("value");
    DataTable.ajax.reload();
})
</code>```

there are two issues
1. first time datatable is loaded no custom data is sent
2. when custom data is sent variable name is "0" and value is select value which is correct but how to change the variable name

答:
i managed to make it work as follows</p>

```<code>var select=1;
var DataTable=$('#mygradedcalls_table').DataTable( {

    "lengthMenu": [[10,25,50,100, -1], [10,25,50,100, "All"]],
    "processing": true,
    "serverSide": true,
    "ajax":{ url:'../Queries_PHP/grad/getAllMyGradedCalls.php',type: 'POST',dataType: "json",data:function (d) {
        d.range = select;
    }
    }
} );

$('.range').click(function () {
    select=$(this).attr("value");
    DataTable.ajax.reload();
})
</code>```

Body:
I'm using datatables and data is loaded with AJAX with custom data
but on custom data refrence variable is changed and ajax is reloaded the custom data value is not changed

 var range=1;
var DataTable=$('#tableid_table').DataTable( {
    "lengthMenu": [[10,25,50,100, -1], [10,25,50,100, "All"]],
    "processing": true,
    "serverSide": true,
    "ajax":{ url:'phpqueryfile.php',type: 'POST',dataType: "json","data": {
        "range": select
    }}
} );

$('.range').click(function () {
    alert($(this).attr("value"));
    select=$(this).attr("value");
    DataTable.ajax.reload();

})

when range click is called and range is changed to any other value, ajax is reloaded with range=1

Edit: i managed to send data after changing

var select=1;
var DataTable=$('#mygradedcalls_table').DataTable( {

    "lengthMenu": [[10,25,50,100, -1], [10,25,50,100, "All"]],
    "processing": true,
    "serverSide": true,
    "ajax":{ url:'../Queries_PHP/grad/getAllMyGradedCalls.php',type: 'POST',dataType: "json",data:function (range) {
        Object.assign(range, select);
        return range;
    }
    }
} );

$('.range').click(function () {
    select=$(this).attr("value");
    DataTable.ajax.reload();
})

there are two issues
1. first time datatable is loaded no custom data is sent
2. when custom data is sent variable name is "0" and value is select value which is correct but how to change the variable name

Body:
i managed to make it work as follows

var select=1;
var DataTable=$('#mygradedcalls_table').DataTable( {

    "lengthMenu": [[10,25,50,100, -1], [10,25,50,100, "All"]],
    "processing": true,
    "serverSide": true,
    "ajax":{ url:'../Queries_PHP/grad/getAllMyGradedCalls.php',type: 'POST',dataType: "json",data:function (d) {
        d.range = select;
    }
    }
} );

$('.range').click(function () {
    select=$(this).attr("value");
    DataTable.ajax.reload();
})


问:
Hdfs put VS webhdfs
I'm loading 28 GB file in hadoop hdfs using webhdfs and it takes ~25 mins to load.

I tried loading same file using hdfs put and It took ~6 mins. Why there is so much difference in performance?

What is recommended to use? Can somebody explain or direct me to some good link it will be really helpful.

Below us the command I'm using

```<code>curl -i --negotiate -u: -X PUT "http://$hostname:$port/webhdfs/v1/$destination_file_location/$source_filename.temp?op=CREATE&overwrite=true"
</code>```

this will redirect to a datanode address which I use in next step to write the data.

答:
The difference between HDFS access and WebHDFS is scalability due to the design of HDFS and the fact that a HDFS client decomposes a file into splits living in different nodes.  When an HDFS client access file content, under the covers it goes to the NameNode and gets a list of file splits and their physical location on a Hadoop cluster.

It then can go do DataNodes living on all those locations to fetch blocks in the splits in parallel, piping the content directly to the client.

WebHDFS is a proxy living in the HDFS cluster and it layers on HDFS, so all data needs to be streamed to the proxy before it gets relayed on to the WebHDFS client.  In essence it becomes a single point of access and an IO bottleneck.

Title: Hdfs put VS webhdfs

Body:
I'm loading 28 GB file in hadoop hdfs using webhdfs and it takes ~25 mins to load.

I tried loading same file using hdfs put and It took ~6 mins. Why there is so much difference in performance?

What is recommended to use? Can somebody explain or direct me to some good link it will be really helpful.

Below us the command I'm using

curl -i --negotiate -u: -X PUT "http://$hostname:$port/webhdfs/v1/$destination_file_location/$source_filename.temp?op=CREATE&overwrite=true"

this will redirect to a datanode address which I use in next step to write the data.