text:
Q: How to disable other divs coming from loop except the clicked one I have some li tags whose data is coming from a loop. When I click any li tag it will become active by changing its image and will store into localstorage so that on refresh the clicked one is still active. Here when we click, an active object is adding to json the clicked li tag and stores it in localstorage. Now the problem is when I click again on the clicked li  tag or outside it, it's toggling the earlier image, which should not be happening. Again, other li tags should be disabled except the clicked one. Here is the code below https://stackblitz.com/edit/angular-skzgno?file=src%2Fapp%2Fapp.component.ts
app.component.html
<hello name="{{ name }}"></hello>

  Start editing to see some magic happen :)

  {{item.id}}
  {{item.name}}

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  statusdata: any;

  ngOnInit() {
    this.statusdata = [
      { id: 1, name: "Angular 2" },
      { id: 2, name: "Angular 4" },
      { id: 3, name: "Angular 5" },
      { id: 4, name: "Angular 6" },
      { id: 5, name: "Angular 7" }
    ];

    this.statusdata.forEach(item => {
      this.getCacheItemStatus(item);
    });
  }

  toggleActive(item, activeStatus = true) {
    item.active = activeStatus;
    localStorage.setItem(`item:${item.id}`, JSON.stringify(item));
  }

  getCacheItemStatus(item) {
    const cachedItem = localStorage.getItem(`item:${item.id}`);
    if (cachedItem) {
      const parse = JSON.parse(cachedItem); // Parse cached version
      item.active = parse.active; // If the cached storage item is active
    }
  }
}

A: It looks to me like you just need to add some logic to your toggleActive method. You could check if any items are active before deciding whether or not to do anything about the click. Does something like this solve your problem?
toggleActive(item, activeStatus = true) {
   if(item.active || !this.statusdata.some(d => d.active)){
      item.active = activeStatus;
      localStorage.setItem(`item:${item.id}`, JSON.stringify(item));
   }
}


text:
Q: Highlighting a search term in a query? I'm having trouble highlighting a search term within a query. If a user searches "Jesus", all verses that contain "Jesus" will be listed and paginated. I want to highlight the search query in all of these passages.
Let's say I search for "Jesus", and some 10 verses pop up, I want all instances of Jesus on every page to be highlighted.
My PHP code:
index: http://pastebin.com/vTdy79er
bible database: http://www.mediafire.com/?00x4fnbn1vr4nch
I have no idea how to go about doing this.
my select statement for my queries:
$searchResult = $dbLink->prepare("SELECT   bsect, bname, bnum, cnum, vnum, vtext,                                             MATCH    (bname, vtext)
AGAINST  ('$searchQuery' IN BOOLEAN MODE)
AS       relevance
FROM     kjv
WHERE    MATCH (bname, vtext)
AGAINST  ('$searchQuery' IN BOOLEAN MODE)
ORDER BY relevance
DESC
$limit");

The code that actually displays my results (bible name chapter number : verse number and then verse text:
while ($searchResult->fetch())
{
print ("$bname $cnum:$vnum");
print ("
$vtext
");
}

A: I believe you already do it here:
$output = str_replace($_GET[phrase],"" . $_GET[phrase] . "",$output);

even if I would suggest to change the code like this:
$output = str_replace($_GET['phrase'],''.$_GET['phrase'].'',$output);

or even better, use a  tag and a class, and then assign all the CSS that you want to that class and make it easier to change in the future
EDIT/ADD
with your last updated message, this is what you have to do (if I understand your code correctly)
print ("
$vtext
");

change it to (assuming that $searchQuery is the variable that contain that string that is searched for
echo '
'.(str_replace($searchQuery, ''.$searchQuery.'', $vtext).'
';

I also like better echo than print, but is personal preference.  For sure you want to avoid the " and use the ' when possible as it will speed up PHP as the engine will not have to parse the whole string to find variables.. but again, personal preference

A: Try this.
jQuery SearchHighlight plugin. Demo and implementation are provided.

A: I did not look at your code but something like this should work:
echo str_replace($searchWord, '' . $searchWord . '', $row['verse']);

redpajama_set_name: RedPajamaStackExchange


text:
Q: CMD Installation of SQL Server Express I am installing SQL Server 2012 from cmd I pass parameter SECURITYMODE = SQL for installing SQL Server on mixed mode instead of Windows Authentication mode but it is installing in windows authentication mode.
Here is my parameters
/q /IACCEPTSQLSERVERLICENSETERMS /ACTION=Install /FEATURES=SQLEngine /INSTANCENAME=SQLEXPRESS /UpdateEnabled=False /SECURITYMODE=SQL /SAPWD=XYZ


text:
Q: Login with facebook error, codeigniter invalid url I am working on a project. I want the user login with facebook. But after the facebook authentication, I get this error:

Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a sub-domain of one of the App's domains.

I searched on Google for a long time and everytime I get this answer that there may be a problem in my facebook application domain name.
I changed my fb application again and again but everytime I get the same error.
Some settings of my facebook application are:

App Domains:     superhitdomains.com

  Site URL:        http://superhitdomains.com

  My view page is :

Login with facebook
and my controller is:
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Social extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        parse_str( $_SERVER['QUERY_STRING'], $_REQUEST );
        $CI = & get_instance();
        $CI->config->load("facebook",TRUE);
        $config = $CI->config->item('facebook');
        $this->load->library('Facebook', $config);
    }

    public function fb_request()
    {
       $userId = $this->facebook->getUser();
       if($userId == 0)
       {
          $data = array(
            'redirect_uri'=> base_url().'social/handle_user_fb_login',
            'scope'=>'email'
          );
          redirect($this->facebook->getLoginUrl($data));
          //print_r($data); exit;
       }
       else
       {
         // Get user's data and print it
         $user = $this->facebook->api('/me');
         print_r($user);
       }
    }

    public function handle_user_fb_login()
    {
        $userId = $this->facebook->getUser();
        if($userId !=0)
        {
            $user = $this->facebook->api('/me');
            print_r($user);
        }
        else
        {
            echo 'could not connected with facebook';
        }
    }
}

Can anyone help me what is wrong with my code?
Thanks

A: I think it's safe to asume that your base_url().'social/handle_user_fb_login' is an invalid url to redirect the user with. Check your Facebook app and make sure that base_url() indeed is mentioned as either canvas url or website url.
This is something Facebook enforces so that their own site can redirect you accordingly and not directly send you to (others) malicious sites.


text:
Q: jQuery Crossslide alternative? Photo moving into a direction I am developing a website for a church. As you can imagine, a church is quite tall in height. If you place a photo of that building into a horizontal banner of a size of let's say 700x200 there's no way you will see much of the building in the photo.
I can't really change much of the design anymore so I searched around and found Crossslide:
http://tobia.github.com/CrossSlide/
If you scroll down to the 2nd example (Slide and cross-fade) you will see that one image is shown and it goes from top to bottom so to speak. I tried implementing this script but failed and gave up after many, many hours. Another issue is that the creater of that plugin doesn't give any more support. So now I am hoping if you guys/girls have alternative idea's / plugin's.
We do not want to use Flash though. So jQuery would be the best solution. Does anyone know a nice plugin that does that CrossSlide did in the 2nd example?
Thank you.

A: I know this is old, but I'm guessing you are trying it with just 1 image.
I just got done messing with this myself and had that same issue, added another module even with the same image and it works perfectly fine.
Example:
var $image = 'images/our_practice_banner.jpg'

$('#banner').crossSlide({
  loop: 1,
  fade: 1
}, [
  {
    src:  $image,
    from: 'top right 1.5x',
    to:   'center center 1x',
    time: 4
  },{
    src:  $image,
    from: 'center center 1x',
    to:   'center center 1x',
    time: 4
  }
]);


text:
Q: params[:page] in will_paginate Gem will_paginate is used in our Rails controller:
 @module_actions = @module_actions.page(params[:page]).per_page(30)

Here what's the use of params[:page]? Does 0 of params[:page] mean displaying the first page of the @module_actions (there are 30 records on one page)?

A: The params[:page] = 0 won't going to work. For displaying first page, it should be params[:page] = 1 i.e the link should be
 localhost/something?page=1
 localhost/something?page=2

by default, even if you remove ?page=1 it will show first page content i.e
localhost/something?page=1

is same as
localhost/something

A: Here page means the page number you want to view. Each page consists of some sprecific number of records which you can either set or use default. The range for page starts from 1 and can go to any further. If you have 100 records for @module_actions then see below output.
@module_actions = @module_actions.page(1).per_page(30) # 1-30 records
@module_actions = @module_actions.page(2).per_page(30) # 31-60 records
@module_actions = @module_actions.page(3).per_page(30) # 61-90 records
@module_actions = @module_actions.page(4).per_page(30) # 91-100 records
@module_actions = @module_actions.page(5).per_page(30) # empty array

And if you try to access records with page 0 you will get an error.
@module_actions = @module_actions.page(0).per_page(30) # Throws RangeError: invalid page: 0


text:
Q: Unselect multiple values in Filter I want vba to unselect the the give colour from the column filter
ActiveSheet.Range("$A$1:$AK$10000").AutoFilter Field:=11, Criteria1:="<>red", Operator:=xlOr, _
    Criteria2:="<>Blue", Operator:=xlOr, Criteria3:="<>pink", _
    Operator:=xlFilterValues

A: Please, test the next code. It will elimnate one from the three mentioned colors (if you write it in InputBox. If nothing is written there, the filter will be configured to use (exclude) all three (pink, blue, red):
Sub ExcludeFilterCondition()
 Dim sh As Worksheet, lastRK As Long, arrInit, arrK, exclCol As String
 Dim mtch, i As Long, dict As New Scripting.Dictionary

 Set sh = ActiveSheet 'use here the sheet you need
 lastRK = sh.Range("K" & sh.rows.count).End(xlUp).row

 arrInit = Split("red,blue,pink", ",")
 exclCol = InputBox("Please, write a color name to be excluded from the filter criteria", "Exclude one color")

 If exclCol <> "" Then arrInit = filter(arrInit, exclCol, False)

 arrK = sh.Range("K2:K" & lastRK).Value2 'place the range in an array for faster iteration
 For i = 1 To UBound(arrK)                             'place in the array to be used as criteria only colors not existing in arrInit
    mtch = Application.match(arrK(i, 1), arrInit, 0)
    If IsError(mtch) Then
        dict(arrK(i, 1)) = vbNullString
    End If
 Next i

 'Place the filter for all existing colors, EXCEPT the ones in (processed) arrInit:
 sh.Range("$A$1:$K$100").AutoFilter field:=11, Criteria1:=dict.Keys, Operator:=xlFilterValues
End Sub

As I said in my comment, your code as you show could not work, from two reasons.

*

*No more than two conditions of "does not equal" type are allowed;

*Even using it for two (allowed) conditions, xlOr operator excludes each other...


text:
Q: UWP losing serialize data with release mode I am trying to make a Diary application in UWP, using Visual Studio Community 2015. So All diary entries are kept in an ObservableCollection (of type DiaryEntry which has three strings). In the OnSuspending method of the App class I serialize (using XmlSerializer) and save the ObservableCollection to the LocalFolder of the app. In the OnLaunched method of the App class I deserialize the data and place it in the ObservableCollection again.
When I run this app in debug mode it is working 100% every time, but in release mode I lose the ObservableCollection once I close and open the app again. Other times it works once or twice but I still lose the data. What I would like to know is how can I get my app working in release mode?
These are the methods I am using:
        private async void SaveCollection(string xml)
    {
        //Serializing our observablecollection and saving it to the local folder
        StorageFile sf = await ApplicationData.Current.LocalFolder.CreateFileAsync("Diary.txt", CreationCollisionOption.ReplaceExisting);
        await Windows.Storage.FileIO.WriteTextAsync(sf, xml);

    }

    private async Task<string> GetSavedCollection()
    {
        try
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("Diary.txt");

            string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

            return text;
        }
        catch (FileNotFoundException e)
        {
            return "";
        }

    }

    public static string ToXml(ObservableCollection<DiaryEntry> d)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<DiaryEntry>));
        StringBuilder stringBuilder = new StringBuilder();
        XmlWriterSettings settings = new XmlWriterSettings()
        {
            Indent = true,
            OmitXmlDeclaration = true,
        };

        using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, settings))
        {
            serializer.Serialize(xmlWriter, d);
        }
        return stringBuilder.ToString();
    }

    // Deserialize from xml
    public static ObservableCollection<DiaryEntry> FromXml(string xml)
    {
        if (xml == "")
        {
            return new ObservableCollection<DiaryEntry>();
        }

        XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<DiaryEntry>));
        ObservableCollection<DiaryEntry> value;
        using (StringReader stringReader = new StringReader(xml))
        {
            object deserialized = serializer.Deserialize(stringReader);
            value = (ObservableCollection<DiaryEntry>)deserialized;
        }

        return value;
    }

This is how I call these methods:
Diaries = FromXml(await GetSavedCollection());
SaveCollection(ToXml(Diaries));

A: It's hard to say for sure without a full repro of your code (see https://stackoverflow.com/help/mcve) but I suspect it's to do with a misunderstanding of the app lifecycle and where you have added your code to the OnLaunched and OnSuspending methods.
To understand the lifecycle, please see the docs here and this blog article.
Now those methods.
Let's deal with OnSuspending first as that's simpler. Your code should look like this:
private void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();

    SaveCollection(ToXml(Diaries));

    deferral.Complete();
}

Note that if you're calling SaveCollection after deferral.Complete(); it may not finish before the app is terminated and could be the cause of not having
The OnLaunching method is more complicated. I suspect you have code like this:
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
    //TODO: Load state from previously suspended application
    Diaries = FromXml(await GetSavedCollection());
}

This might seem the logical thing to do based on the TODO comment in the template but won't be right for your scenario where you want to always load from disk when restarting the app. The above wouldn't, for example, load the content when the app previously close by the user. I assume you'd want to load the diary entries then too. (Because you haven't provided full repro steps I can't know exactly how you're testing and recreating the behavior you're seeing.)
Instead, load the Diaries, if need be, just before the 'PrelaunchActivated check.
if (Diaries == null)
{
    Diaries = FromXml(await GetSavedCollection());
}

if (e.PrelaunchActivated == false)

OR
It's an issue with how you've defined and are calling SaveCollection.
You've defined SaveCollection as async void. This is bad. The only things that should be async void are event handlers. You should have defined it as async Task and awaited the call to it:
private async Task SaveCollection(string xml)
{
    System.Diagnostics.Debug.WriteLine(xml);

    //Serializing our observablecollection and saving it to the local folder
    StorageFile sf = await ApplicationData.Current.LocalFolder.CreateFileAsync("Diary.txt", CreationCollisionOption.ReplaceExisting);
    await Windows.Storage.FileIO.WriteTextAsync(sf, xml);
}

await SaveCollection(ToXml(Diaries));

Without awaiting this call it may not complete correctly. That this behavior is more obvious under .NetNative compilation would not surprise me.
Or it may be a combination of both issues.


text:
Q: Issue with Navigation Component Duplicate NavArgs I have a fragment:
class SomeFragment {
    private val args by navArgs<SomeFragmentArgs>()
}

this fragment is used in two navigation graph:
first_nav.xml
....
<fragment
    android:id="@+id/initialFragment"
    android:name="com.example.InitialFragment"
    android:label="Initial Fragment">
    <action
        android:id="@+id/action_to_some_fragment"
        app:destination="@id/someFragment" />
</fragment>
<fragment
    android:id="@+id/someFragment"
    android:name="com.example.SomeFragment"
    android:label="Some Label">
    <argument
        android:name="someType"
        app:argType="com.example.someType"/>
</fragment>
....

second_nav.xml
....
<fragment
    android:id="@+id/initialFragment2"
    android:name="com.example.InitialFragment2"
    android:label="Initial Fragment">
    <action
        android:id="@+id/action_to_some_fragment"
        app:destination="@id/someFragment" />
</fragment>
<fragment
    android:id="@+id/someFragment"
    android:name="com.example.SomeFragment"
    android:label="Some Label">
    <argument
        android:name="someType"
        app:argType="com.example.someType"/>
</fragment>
....

But when I build the project for release R8 throws:
R8: Program type already present: com.example.SomeFragmentArgs$Companion
Can anyone help me on this?

A: I am facing this issue too. We are using multiple modular developing and the direction class are generated in different modules. So that there are several FragmentDirections in everywhere and cause R8 Program type already present since they all got companion object.
There are two solutions/workarounds.

*

*Isolate this fragment into an independent navigation.xml

In your case you can write a some_fragment_nav.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:startDestination="@id/someFragment"
android:id="@+id/some_fragment_nav">

<fragment
    android:id="@+id/someFragment"
    android:name="com.example.SomeFragment"
    android:label="lable">

    <action
        android:id="@+id/what_ever_action_you_want"
        app:destination="@id/share_this_id_to_ids" />

    <argument
        android:name="someType"
        app:argType="com.example.someType"/>

</fragment>

</navigation>

and use
<include app:graph="@navigation/some_fragment_nav"/>

in both of your navigation graphs. That will work. If you are using multi-modular developing. You need to share action id by writing your id into ids.xml.

*Copy and past SomeFragment to different naming like SomeFragment1.kt SomeFragment2.kt. And there won't be any R8 Program type already present too. Further more you can make SomeFragment as open class and SomeFragment1 extend SomeFragment with empty implementation.

My personal prospects.. 2 is better than 1 since they all look like workarounds to me. Until jetbrains change the rules of generated FragmentDirection class.


text:
Q: finding the value of the points in a chart I have made a chart on my form.
I want the user to see the value, x_value and y_value of each part in a balloon by clicking on that part.
The ballon shoud disappear when the user moves the mouse.
How can I do that?

A: You could do something like this:
    ToolTip tooltip = new ToolTip();
    Point? clickPosition = null;

    void chart1_MouseMove(object sender, MouseEventArgs e)
    {
        if (clickPosition.HasValue && e.Location != clickPosition)
        {
            tooltip.RemoveAll();
            clickPosition = null;
        }
    }

    void chart1_MouseClick(object sender, MouseEventArgs e)
    {
        var pos = e.Location;
        clickPosition = pos;
        var results = chart1.HitTest(pos.X, pos.Y, false,
                                     ChartElementType.PlottingArea);
        foreach (var result in results)
        {
            if (result.ChartElementType == ChartElementType.PlottingArea)
            {
                var xVal = result.ChartArea.AxisX.PixelPositionToValue(pos.X);
                var yVal = result.ChartArea.AxisY.PixelPositionToValue(pos.Y);

                tooltip.Show("X=" + xVal + ", Y=" + yVal,
                             this.chart1, e.Location.X,e.Location.Y - 15);
            }
        }
    }

Result:

EDIT :
to show the tooltip whenever the mouse move, you can use the following code:
Point? prevPosition = null;
ToolTip tooltip = new ToolTip();

void chart1_MouseMove(object sender, MouseEventArgs e)
{
    var pos = e.Location;
    if (prevPosition.HasValue && pos == prevPosition.Value)
        return;
    tooltip.RemoveAll();
    prevPosition = pos;
    var results = chart1.HitTest(pos.X, pos.Y, false,
                                 ChartElementType.PlottingArea);
    foreach (var result in results)
    {
        if (result.ChartElementType == ChartElementType.PlottingArea)
        {
            var xVal = result.ChartArea.AxisX.PixelPositionToValue(pos.X);
            var yVal = result.ChartArea.AxisY.PixelPositionToValue(pos.Y);

            tooltip.Show("X=" + xVal + ", Y=" + yVal, this.chart1,
                         pos.X, pos.Y - 15);
        }
    }
}

Note that this shows the tooltip on any position of the chart. If you want to show it only when the mouse is near to a series point, you can use a mschart functionality e.g. :
yourSeries.ToolTip = "X=#VALX, Y=#VALY";

(further examples here)


text:
Q: In microservices does it makes sense to have one microservice with two database connections? I'm beginning with microservices but what I'm about to do seems to be a bad practice. Let's imagine I have an user microservice and an order microservice.

Now, if I want to create a report based on user and orders I would need to consume both user and order microservices through their apis. Would it make sense to have a report microservice with database connections to both user and order microservices?

While I was reading microservices.io decomposition section they say that doing joins into our queries becomes harder, so why create endpoints to handle "possible joins"(suggested by the article) for reports instead of giving read access to each database(imagining a database per microservice)?


text:
Q: Convert a Math Equation to output as a float value So I have this line of code:
var maths = anInteger / keyprice;

I print it this line:
textBox1.Text = textBox1.Text + "Converted into: " + maths;

I was wondering how do I make it output a float, say I have anInteger = 42 and keyprice = 24 into a 2dp number?

A: In C# the result of dividing 2 integers is an integer. If you want it a float then cast one of them into a float:
var maths = anInteger / (float)keyprice;
textBox1.Text = $"{textBox1.Text} Converted into: {maths.ToString("n2")}";

If prior to C# 6.0 then:
var maths = anInteger / (float)keyprice;
textBox1.Text = textBox1.Text + "Converted into: " + maths.ToString("n2");


text:
Q: How to print all possible paths of a binary tree given that I have all directly connected nodes as a list in a dictionary? I have a tree with nodes: [1,2,3,4,5] with 1 as root. Can be represented as:

And I have a dictionary having keys as nodes and they contain a list of nodes connected to them,
my_dict = {1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: []}

From this dictionary I want to print all the paths possible from the root to leaf nodes as a list like:
output: [[1,2,4],[1,2,5],[1,3]]

What I have tried is,
l = list()
root = 1
def path_finder(root):
    l.append(root)
    prev = root
    for val in my_dict[root]:
        print(val)
        path_finder(val)
        if root == prev:
            print("End of path")

Which returns:
2
4
End of path
5
End of path
End of path
3
End of path

I am completely stuck at this, any help will be highly appreciated. Thanks in advance :-)

A: You can use a recursive generator:
my_dict = {1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: []}
def get_paths(s, c = []):
  if not my_dict[s]:
     yield c+[s]
  else:
     for i in my_dict[s]:
       yield from get_paths(i, c+[s])

print(list(get_paths(1)))

Output:
[[1, 2, 4], [1, 2, 5], [1, 3]]


text:
Q: Javascript toggle Image source I want to create a simple toggle image control which changes it's image when checked or unchecked. I tried to create a seperate class for it because I intend to add a listener to react to changes of the toggle state and it seemed like a good solution to me. The number of toggleImages will depend on the user so I tried creating them using js.

<html>
  <head>

  </head>
  <body>

    <div id="box">

    </div>

  </body>
  <script>
      class ToogleImage{
        constructor(imgToggled, imgNotToggled, img){
          this.toggled = false;
          this.imgToggled = imgToggled;
          this.imgNotToggled = imgNotToggled;
          this.img = img;
          this.refreshImage();
          this.img.addEventListener('click', function (e) {
            this.toggleState();
            this.refreshImage();
          });
        }
           toggleState(){
            this.toggled!=this.toggled();
          }
           refreshImage(){
            if(this.toggled){
              img.setAttribute('src', this.imgToggled);

            }else{
              img.setAttribute('src', this.imgNotToggled);
            }
          }

      }

      var img = document.createElement("img");
      var toggleImage = new ToogleImage("https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded", "https://www.stackoverflowbusiness.com/hubfs/B2B-SO/images/SO_Talent.svg?t=1515694040462", img);
      document.getElementById('box').appendChild(img)
    </script>

</html>

Problem is that the image will not display. Does anyone know how to fix this?


text:
Q: Python: I am trying to call a function but the expected results won't come This program prompts the user for numbers and when the user inputs 'done', it should give the largest value which was input and the smallest.
The function seems to work just fine for the largest variable. Which successfully takes the value of the first input. Later, the program keeps running, and it updates its value for the biggest value typed until done is pressed, so it will print it.
The Problem that I'm having is with the variable 'smallest'. Once the program runs, we type some numbers. When we insert ' done ', when the function is running, the Minimum (which relates to the variable smallest) will still have the value 'None'. So I'm having problems, through the function, to assign the smallest with the inputted values, so that it loses its None value.
If I run the function 'manually', i.e., I don't use this logic in a function, it'll work just fine and provide the results as expected.
inum = None
largest = None
smallest = None

def primeval(sizest) :
    if sizest is None :
        sizest = inum

while True:
    num = input ('Enter an integer number: ')
    if num == 'done' :
        break
    try:
        inum = int(num)
    except:
        print ('Invalid input')
        continue

    primeval (largest)

    primeval (smallest)

#if largest is None :                   #if done manually it'll work
 #   largest = inum
#if smallest is None :
 #   smallest = inum

  #resume of the code, after the 'manual primeval'

if inum > largest :
    largest = inum
if  inum < smallest :
    smallest = inum

print ('Maximum is', largest)
print ('Minimum is', smallest)

A: I would approach your problem differently:
numbers = []

while True:
    user_input = input ('Enter an integer number (e for end!): ')

    if user_input == 'e':
        break
    try:
        number = int(user_input)
    except:
        print('Invalid input!')
        continue
    numbers.append(number)

if len(numbers):
    print('Maximum is', max(numbers))
    print('Minimum is', min(numbers))

You define a function that has no return value (return statement). In the function you want to work with the value inum, which you do not pass as parameter and which you do not define in the function. You shouldn't do that.
If you prefer a solution without a list:
smallest = None
largest = None

while True:
    user_input = input ('Enter an integer number (e for end!): ')

    if user_input == 'e':
        break
    try:
        number = int(user_input)
    except:
        print('Invalid input!')
        continue

    if smallest is None or largest is None:
        smallest = number
        largest = number
    else:
        if number < smallest:
            smallest = number
        if number > largest:
            largest = number

print('Maximum is', largest)
print('Minimum is', smallest)

In this case it makes sense to initialize the two values for the first time with None.

A: you have to return a value:
def primeval(sizest,inum) :
    if sizest is None:
        sizest = inum
    return sizest

and use it like this:
largest = primeval(largest,inum)


text:
Q: How can I fix this System.OutOfMemoryException error? So, I'm begining ASP.NET, and at the same time learning a small bit of C#, enough to get by making web pages. I just took on the project of making a basic visual calculator, the kind with the fancy buttons that you click. This is my C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ExtraCredit_GraphicCalculator : System.Web.UI.Page
{
    string number1 = "";
    string number2 = "";
    bool EnteringNumber1 = true;
    bool EnteringNumber2 = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        while (EnteringNumber1)
        {

            Enter9.Click += (s, args) =>
            {
                number1 = number1 + "9";
            };

            Enter8.Click += (s, args) =>
            {
                number1 = number1 + "8";
            };
            Enter7.Click += (s, args) =>
            {
                number1 = number1 + "7";
            };
            Enter6.Click += (s, args) =>
            {
                number1 = number1 + "6";
            };
            Enter5.Click += (s, args) =>
            {
                number1 = number1 + "5";
            };
            Enter4.Click += (s, args) =>
            {
                number1 = number1 + "4";
            };
            Enter3.Click += (s, args) =>
            {
                number1 = number1 + "3";
            };
            Enter2.Click += (s, args) =>
            {
                number1 = number1 + "2";
            };
            Enter1.Click += (s, args) =>
            {
                number1 = number1 + "1";
            };
            Enter0.Click += (s, args) =>
            {
                number1 = number1 + "0";
            };
            Result.Text = number1;
        }
    }
}

Just a few things to notice, these Event#.Something each correlate to a number button, so with Enter7.Click, on the click of the button labeled 7, it does something. At the end, the Result.Text correlates to a Label that displays the result. Right now, I just want to be able to see the results of each button click, but I plan to add functions for a second number and math functions like exponents and square roots.
What exactly can I do to fix this error?

A: First of all EnteringNumber1 is always true so your Page_Load method never exits. It only continues to add event handlers which is probably causing your memory error. Know that Page_Load is an event that fires during the initialization portion of the page. You'll typically use this method to set properties in controls and to establish database connections (see Page Life Cycle Overview for more info).
Remember HTML is static, and all asp.net is doing is creating these static html pages on the server. You'll want to remove the infinite loop and let the events register once.
You'll also want to handle some sort of displaying of the value in the click events.
In this scenario, I really don't see much happening in your Page_Load handler. You can create separate event handlers for each button if you want (you could simplify this later). By default, when the user click's a button on the page, a PostBack to the server happens and the server does some calculations and a new version of the page is returned. In the end, you would have something that looks kind of like the following:
protected void Page_Load(object sender, EventArgs e)
{
     if(!Page.IsPostBack()) // we only want this stuff to happen on initial load
     {
         hiddenField.value = 0;
     }
}

protected void Enter9_OnClick(object sender, EventArgs e)
{
    // a postback to the server just happened
    hiddenField.value = (double)hiddenField.value + 9;
}

....
....

Note that this code isn't tested and may not be 100% correct, but it gets you the basic idea on how asp.net works.
Now when you're comfortable with page lifecycle what you REALLY want to do is a) handle the calculations client side in javascript or b) marshall the calls from the client side code to the server (where your computations will happen) and back using simple ajax. Check out jQuery to help with the client side.

A: One big error that I see is that you never set EnteringNumber1 to false, so upon page load you have an infinite loop, and in that infinite loop you are registering event handlers for your buttons repeatedly, which keeps allocating memory.
Dump the loop.  There shouldn't be any need for it. Make sure your result also goes to an input field in your asp so that when another button is pressed, you can "add" the number to the number you've already established.


text:
Q: How to using insert/update callback codeIgniter I have 3 tables, tbl_reservasi, tbl_ruangan, and user.
I want to update my tbl_ruangan.status from Tersedia to Tidak Tersedia.
Here's my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Reservation extends MY_Controller {

public function index()
{
    $this->push_breadcrumb('Reservation', 'reservation');
    // CRUD table
    $this->load->helper('crud');
    $crud = generate_crud('tbl_reservasi');
    $crud->set_subject('Reservasi');

    //Label Fields
    $crud->display_as('kdReservasi','Kode Reservasi');
    $crud->display_as('kd','Ruangan');
    $crud->display_as('id','User');
    $crud->display_as('tanggalMasuk','Tanggal Masuk');
    $crud->fields('kd','id','tanggalMasuk');
    $crud->required_fields('kd','id','tanggalMasuk');

    //Kolom Input dan Callbacks
    $crud->set_relation('kd','tbl_ruangan','{kd} - {kdRuangan} - {jenis} - {namaRuangan}', array('status' => 'Tersedia'));
    $crud->set_relation('id','users','{id} - {email} - {first_name} {last_name}', array('active' => '1'));
    $crud->callback_after_insert(array($this, 'status_update'));

    //Cetak Halaman
    $this->mTitle = "Reservation";
    $this->mViewFile = '_partial/crud';
    $this->mViewData['crud_data'] = $crud->render();
}

function status_update($post_array,$primary_key)
    {
        $_update = array(
            "kd" => $primary_key,
            "status" => 'Tidak Tersedia'
        );
        $this->db->update('tbl_ruangan',$_update, array('kd' => $primary_key));
        return true;
    }

Everytime i insert data, inserting ruangan, user, and tanggalMasuk it doesn't directly change status to Tidak Tersedia. It changes after i insert 2 records with the same values.
All i want only if i insert record from tbl_reservasi, then status from tbl_ruangan change to Tidak Tersedia.


text:
Q: Qt: Display Live Video, One Frame At A Time I have a decoded video frame coming over a distributed bus.  Currently, I am using a QLabel that receives the frame buffer via Qt Signal/Slot and sets it's pixmap.
void VideoViewer::slot_update_view( unsigned char* frame, QSize size )
{
        QImage img( frame, size.width(), size.height(), QImage::Format_RGB888 );
        _label->setPixmap( QPixmap::fromImage( img ).scaledToWidth( width(), Qt::SmoothTransformation ) );
}

This works, but using QLabel feels hacky. Is there a better solution?  Eventually I'd like to draw on top of the video.

A: I'd say, the best way to make it less 'hacky' and more robust is to use some low-level image classes instead of raw pointers to buffers. For example, you could use a representation like the one in OpenCV.
Using plain buffers can be really risky, and bugs will be hard to track.


text:
Q: Click on element that contains a specific alt tag I currently have the following code:

<input name="style" aria-labelledby="styleI0065001" id="input_radio_style_17" type="radio" required="" value="17">

I have about 20 of these on the page sometimes that number changes, what I need to do is to loop over each and find the one that contains a specific alt tag and then click on it.
In the above example I would need to loop through a bunch and find the one that contains alt="Green picture frame" and then click on it.
To start I would loop through each element with SelectStyle like so.
const imgs = await page.$$eval('.SelectStyle', imgs => imgs.map{
    return (img => img.getAttribute('alt'))
});

From here I'm kind of stuck, how would I return the element which matches and then click on it?

A: You can solve that with a CSS attribute selector
const imgs = await page.$$('.SelectStyle img[alt="Green picture frame"]');


text:
Q: HTML window object onclose or closing event Is the window object onclose() or closing() event exposed in HTML/Javascript?

A: You have both onunload() and onbeforeunload() javascript events for that.

A: I think you want the onUnload event.

A: There is no event that lets you determine the difference between a page refresh, form submission, link clicked, or browser closed.
I am guessing that is what you are really after.

A: As suggested epascarello: Events onunload or onbeforeunload you can't use directly - they do not differ between window close, page refresh, form submit, link click or url change.
The only working solution is How to capture the browser window close event?
Popup windows are problematic (bring to front, close event, blocking) and annoying - you should consider using a modal popup instead.


text:
Q: H1 image link has line under it No matter what i try, when i preview it theres no link but when i go on my actual site there is a line underneath.

     test

My css is here: https://pastebin.com/5c9dm0b0
I've looked up every tutorial on how to get rid of it, but its still there.
Any help would be appreciated.

A: Use :
a {
  text-decoration: none!important;
}

A: There is error in your CSS file at line no 31 extra } remove that and try
a {
  text-decoration: none;
}


text:
Q: MySQL select highest amount I'm trying to write a SELECT query that will show the lowest invoice amount of each supplier in the table below. Tried a few solutions but can't get my head around it! Can anyone help? Thank you in advance.

A: For the lowest invoice_price by supplier_name You can use aggregation function MIN with group by
select supplier_name, min(invoce_price)
from my_table
group by supplier_name

A: Use min aggregation function with group by clause
select supplier_name, min(invoice_price) from table_name group by supplier_name

Similarly to get the highest amount, use max aggregation function
select supplier_name, max(invoice_price) from table_name group by supplier_name

A: If you want columns like the invoice number/date, you will need to write 2 queries, I usually prefer to write a tmp table for this sort of task.
DROP TEMPORARY TABLE IF EXISTS tmp_min_value;
CREATE TEMPORARY TABLE tmp_min_value AS
SELECT [key columns eg. supplier], min(invoice_price) as min_invoice_value
FROM supplier_invocies
GROUP BY [key columns eg. supplier];

SELECT is.*
FROM supplier_invoices si
INNER JOIN tmp_min_value tmv
  ON si.supplier_name = tmv.supplier_name
  AND si.invoice_price = tmv.min_invoice_value;

You may get multiple invoices per supplier, if there are multiple invoices with the same invoice price. You can get rid of this by using another join if you need a specific (eg. the last relevant invoice) or just by grouping the relevant columns and using MIN() on the invoice_price again.

A: The answer is quite simple:
SELECT SUPPLIER_NAME, MIN(INVOICE_PRICE)
FROM SUPPLIER_INVOICES
GROUP BY SUPPLIER_NAME;


text:
Q: Equals with row permutation using Pandas I want to check if two data frames have the same rows.
I've tried:
df1.equals(df2)

But it returns False, because rows are not in the same order. Is there any function which check equals, but with row permutation? Thank You very much for any help.

A: In pandas the index is important , if the index different even all value same in the rows, we should still treat it as different , however we can do merge
df1.merge(df2, indicator=True, how='outer')['_merge'].eq('both').all()


text:
Q: how can i retry a fetch request when an 408 or say an 503 error is receved in reactjs i am fetching data from a sever and sometime the request take so long and the sever responds with a 408 status
so my code looks like this
export class ResponseError extends Error {
  public response: Response;

  constructor(response: Response) {
    super(response.statusText);
    this.response = response;
  }
function parseJSON(response: Response) {
  if (response.status === 204 || response.status === 205) {
    return null;
  }
  return response.json();
}
function checkStatus(response: Response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const error = new ResponseError(response);
  error.response = response;
  throw error;
}
export async function request(
  url: string,
  options?: RequestInit,
): Promise<{} | { err: ResponseError }> {
  const fetchResponse = await fetch(url, options);
  const response = checkStatus(fetchResponse);
  return parseJSON(response);
}

how can i retry the request if the response status code 408 is received

A: If you use axios in your code for fetching api you can try below code
axios.create().interceptors.response.use(
        response => response,
        error => {
            if (error.response.status === 503){
                axios.create().get("YOUR_URL").then((response)=>{
                })
            }
        }
    )


text:
Q: How to select a list item present under UL in selenium webdriver below is the code and i want to select the first list item i,e VAN.

<button id="equipment-dropdown-btn" class="btn strip-radius btn-default dropdown-toggle col-xs-10 noSidePad" data-bind="html: selectedEquipment(), css: {'has-error' : $parent.errorMessage() && selectedEquipment() == 'Select...'}" aria-expanded="false" data-toggle="dropdown" type="button">Flatbed</button>
<button class="btn btn-default equipt-toggle dropdown-toggle col-xs-2 noSidePad" aria-expanded="false" data-toggle="dropdown" type="button">

Toggle Dropdown
</button>

**Van**

I am stuck , that should i first identify the drop down field and then select the list.
Any help or lead on this question is greatly appreciated.

A: First try with below Xpath
//ul[@id='equipmentType']/li/a[contains(.,'**Van**')]

If there is a dropdown which having this value then Yes you need to click on that dropdown first
driver.findElement(YOUR Locator)).click();
List<WebElement> options = select.findElements(By.xpath("//ul[@id='equipmentType']/li"));
for (WebElement option : options) {
  if("**Van**".equals(option.getText()))
    option.click();
}

Hope it will help you :)

A: You will be required to first click on the drop down button which you can get by Xpath to display(or toggle) the select list
driver.findElement(By.Xpath(".//button[//span[text()='Toggle Dropdown']]")).click();
and then
driver.findElement(By.Xpath(".//ul[@id='equipmentType']//[text()='**Van*']")).click();
you can use other values in place of **Van** to make it more generic


text:
Q: Horizontal scrolling like Instagram in Codename One In my Codename One app, I don't need an horizontal scrolling identical to Instagram, but similar to some aspects.
Please look at this video, that shows a horizontal scrolling in Instagram:
https://www.informatica-libera.net/videoLavoro/instagramScrolling.mp4
The main functionality that I need (and that is different from the standard horizontal scrolling), is the ability to scroll a Container only if the finger movement is more that a given horizontal space (we can suppose 20mm), otherwise the Container is restored to the position before the scrolling (like Instagram does).
Moreover, if the scrolling is "accepted" (that means more that 20mm), the Container will be automatically horizontally scrolled to make an inner Component full visible at the left of the horizontal space.
Example:
Suppose that I have a Container (with BoxLayout.x()) that contains the Components A, B, C and suppose that A, B and C have a width identical to the 75% of the screen width.
So, at the app start, A is full visible, B is visible only for a small part, C is not visible. I need a scrolling like Instagram that, if accepted (the scrolling is more than 20mm), makes B full visible in the same position of A (otherwise it undoes the scrolling).
So, after this kind of horizontal scrolling, A will be not visible, B full visible, C visible only for a small part.
Any suggest to implement this behaviour (like in this example) with Codename One? Thank you

A: You need Tab with the swipeActivated set to true. The only downside to Tab is you can't set only one side to be visible. Both left and right will be set to be visible.
From your analogy above, part of both A and C will be visible when B is fully visible, only by the size you set with setTabsContentGap().
Some code to get you started:
Tabs tabs = new Tabs();
tabs.setSwipeActivated(true);
tabs.setAnimateTabSelection(true);
tabs.setEagerSwipeMode(true);
tabs.setTabsContentGap(CN.convertToPixels(20, true));
tabs.setUIID("Container");
tabs.setTabUIID("Container");
tabs.getTabsContainer().setUIID("Container");
tabs.getContentPane().setUIID("Container");

And you can start filling your tab with:
tabs.addTab("", myContent);


text:
Q: Switching an image on hover over text / Without the use of jQuery I am making a portfolio page as a school project. My idea is to have an image with titles underneath and whenever I hover over a headline (let's say there will be a headline for Design Manual, Animation, Storyboard etc.) the image will change to a one corresponding to the headline that can be clicked and will lead to a subpage with more information about the chosen theme. I can't use any jQuery yet only javascript.
I wrote this piece of code that is working however it is too long and I would like to know if there is a shorter possibility. I was thinking an array with switch function? However I am very new to javascript so I could not put it together myself when I tried. Any help is appreciated.
let thumbnail = document.querySelector("#thumbN");

let buttonOne = document.querySelector("#ButtonOne");
let buttonTwo = document.querySelector("#ButtonTwo");
let buttonThree = document.querySelector("#ButtonThree");
let buttonFour = document.querySelector("#ButtonFour");
let buttonFive = document.querySelector("#ButtonFive");
let buttonSix = document.querySelector("#ButtonSix");
let buttonSeven = document.querySelector("#ButtonSeven");
let buttonEight = document.querySelector("#ButtonEight");
let buttonNine = document.querySelector("#ButtonNine");
let buttonTen = document.querySelector("#ButtonTen");

buttonOne.addEventListener("mouseover", doBackgroundOne);
buttonOne.addEventListener("mouseout", removeBackOne);

buttonTwo.addEventListener("mouseover", doBackgroundTwo);
buttonTwo.addEventListener("mouseout", removeBackTwo);

buttonThree.addEventListener("mouseover", doBackgroundThree);
buttonThree.addEventListener("mouseout", removeBackThree);

buttonFour.addEventListener("mouseover", doBackgroundFour);
buttonFour.addEventListener("mouseout", removeBackFour);

buttonFive.addEventListener("mouseover", doBackgroundFive);
buttonFive.addEventListener("mouseout", removeBackFive);

buttonSix.addEventListener("mouseover", doBackgroundSix);
buttonSix.addEventListener("mouseout", removeBackSix);

buttonSeven.addEventListener("mouseover", doBackgroundSeven);
buttonSeven.addEventListener("mouseout", removeBackSeven);

buttonEight.addEventListener("mouseover", doBackgroundEight);
buttonEight.addEventListener("mouseout", removeBackEight);

buttonNine.addEventListener("mouseover", doBackgroundNine);
buttonNine.addEventListener("mouseout", removeBackNine);

buttonTen.addEventListener("mouseover", doBackgroundTen);
buttonTen.addEventListener("mouseout", removeBackTen);

function doBackgroundOne() {
    thumbnail.classList.add('BackOne');
    console.log("fatality");
}

function removeBackOne() {
    thumbnail.classList.remove('BackOne');
}

function doBackgroundTwo() {
    thumbnail.classList.add('BackTwo');
    console.log("fatality");
}

function removeBackTwo() {
    thumbnail.classList.remove('BackTwo');
}

function doBackgroundThree() {
    thumbnail.classList.add('BackThree');
    console.log("fatality");
}

function removeBackThree() {
    thumbnail.classList.remove('BackThree');
}

function doBackgroundFour() {
    thumbnail.classList.add('BackFour');
    console.log("fatality");
}

function removeBackFour() {
    thumbnail.classList.remove('BackFour');
}

function doBackgroundFive() {
    thumbnail.classList.add('BackFive');
    console.log("fatality");
}

function removeBackFive() {
    thumbnail.classList.remove('BackFive');
}

function doBackgroundSix() {
    thumbnail.classList.add('BackSix');
    console.log("fatality");
}

function removeBackSix() {
    thumbnail.classList.remove('BackSix');
}

function doBackgroundSeven() {
    thumbnail.classList.add('BackSeven');
    console.log("fatality");
}

function removeBackSeven() {
    thumbnail.classList.remove('BackSeven');
}

function doBackgroundEight() {
    thumbnail.classList.add('BackEight');
    console.log("fatality");
}

function removeBackEight() {
    thumbnail.classList.remove('BackEight');
}

function doBackgroundNine() {
    thumbnail.classList.add('BackNine');
    console.log("fatality");
}

function removeBackNine() {
    thumbnail.classList.remove('BackNine');
}

function doBackgroundTen() {
    thumbnail.classList.add('BackTen');
    console.log("fatality");
}

    function removeBackTen() {
    thumbnail.classList.remove('BackTen');
}

HTML

        First Site

        Redesign

        Storyboard

        Animation

        Interactive

        Group project

        Abeona

        Visual identity

        Reportage

        Stronger together

A: How about you loop through all the buttons on your page and add event listeners :
Steps

*

*Get all buttons on your page

*Loop through buttons collection

*While designing your HTML you can apply specific css class as an identifier
on buttons you would like to add event listen to, use this check
within loop.

*Define just one mouseover and mouseout functions to add and remove classes, attach them as
event listener and pass class name via parameter (you may define
these classes in some pattern i.e. buttonid + class )

sample code below
var allButtonsOnYourPage = document.getElementsByTagName('button');
for (var i = 0; i < allButtonsOnYourPage.length; i++) {
    var button = allButtonsOnYourPage[i];
    //check button's class
var appliedCssClass = button .className
    if(appliedCssClass == 'yourCustomClass'){
    button.addEventListener("mouseover", applyBackground, false);
    addEventListener('mouseover', applyBackground.bind(null, event, 'pass class to be applied'));
   addEventListener('mouseout', applyBackground.bind(null, event, 'pass class to be removed'));

}

}

function applyBackground(applyThisclass) {
    document.querySelector("#thumbN").classList.add(applyThisclass);

}

function removeBackground(removeThisclass) {
    document.querySelector("#thumbN").classList.remove(removeThisclass);
}


text:
Q: How to read input from tkinter Entry in jupyter notebook python

I am trying the read the Input Entered in Ticker Entry and analyze later in the code. But for now, I am simply trying to read input from Ticker and Insert the same value into label Current price. Followed is my code. and I am getting the error for which I attached the screen shot.

daily_heading = Label(top, text = "Daily Analysis").place(x = 0, y = 20)
intra_day_heading = Label(top, text = "Intraday  Analysis").place(x = 330,y = 20)

daily_analysis = Button(top,text = "Daily Analysis", command=insert_data).place(x = 30,y = 670)

intraday_analysis = Button(top,text = "Intraday Analysis").place(x = 330,y = 670)
def insert_data():
   print("You enterted followed symbol")
   symbol = str(top.user_name_input_area.get())
   print(symbol)
   #top.current_price_input_area.insert(0, symbol)


text:
Q: How to get data type from string javascript I have a few strings
strings = [
    "String",
    "Object",
    "Boolean"
]

and I would like to use them to declare new objects
for(var i = 0; i < strings.length; i++){
    var x = new strings[i];
}

but instead I get this error:
TypeError: string is not a function
  at Object.<anonymous> (/Users/path/code.js)
  at Object.<anonymous> (/Users/path/code.js)
  at Module._compile (module.js:456:26)

How can I treat strings as their underlying types?

Aside:
I know that I could do something like
type_map = {
    String: String,
    Object: Object,
    Boolean: Boolean
}

and then go
for(var i = 0; i < strings.length; i++){
    var x = new type_map[strings[i]];
}

which works, but I'm looking for something slightly more elegant if it exists.

A: What's wrong with the obvious?
var i, x, constructors = [
    String,
    Object,
    Boolean
];

for(i = 0; i < constructors.length; i++){
    x = new constructors[i];
}

Bear in mind that anything in JS is an object (including "class names") and may be used, pretty much, however you want.

A: The constructors for these classes are properties of the global object.
For example, in a browser, you could do
console.log(window['String'] === String); // true
var str = new window[strings[0]]();
console.log(str); // ""

A: Found a great way to do it with the eval function
strings = [
    "String",
    "Object",
    "Boolean"
]

for(var i = 0; i < strings.length; i++){
    var x = new (eval(strings[i]));
}

so to summarize eval("String") === [Function: String]


text:
Q: Loading next level Unity c# Heres my first attempt at loading the next level upon reaching "Goal"
public int CurrentLevel = 0;
public static int maxlevel = 3;

public void CompleteLevel()
{
    if (CurrentLevel < maxlevel)
    {
        CurrentLevel += 1;
        SceneManager.LoadScene(CurrentLevel);
    }
    else
        print("you win");
}

This is in another class...
void OnTriggerEnter(Collider other)
{
    if (other.transform.tag == "DeathObject")
        Die();
    if (other.transform.tag == "Goal")
    Manager.CompleteLevel();
}

It ended up loading the first level, went to the second, then it would repeat the second map when i reached goal. Another thing it would do is skip to the last level from the first or second level.. not sure whats going on there. Heres the second thing i tried:
public void LevelPassTest()
{
    if (Application.loadedLevel > 4)
        Application.LoadLevel(Application.loadedLevel + 1);
        else
    print("win");
}

This is in another class....
void OnTriggerEnter(Collider other)
{
    if (other.transform.tag == "DeathObject")
        Die();
    if (other.transform.tag == "Goal")
    Manager.LevelPassTest();
}

I'm not sure why, but sometimes it doesn't load the next level, it worked for a while then stopped, after I reset unity it works again, so I'm not sure if it's my code or unity... I get a warning message that says "Warning  CS0618  'Application.loadedLevel' is obsolete: 'Use SceneManager to determine what scenes have been loaded'" and "Warning   CS0618  'Application.LoadLevel(int)' is obsolete: 'Use SceneManager.LoadScene'" I'm new to coding and completely lost on this. spent 4 hours trying to fix it. What are these warnings? can they be effecting the loading? I was also wanting to be able to save the value of the level so i can use it in game saves, and attach high scores to it. I tried using this in my first attempt, but it didn't work how i was hoping. (CurrentLevel)

A: Application.LoadLevel and the rest are obsolete as of Unity 5. You have to use SceneManager instead.
So Application.LoadLevel() is now SceneManager.LoadScene().
You must also include using UnityEngine.SceneManagement;
See here: http://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html
All it takes is a quick Google.

A: *

*Are your scenes correctly added to the Build Settings?
Go to File > Build Settings... and check in "Scenes In Build" whether all your scenes from scene #0 to scene #3 are added the way you need them.

*The first example you gave should work, however you have to make sure, that your first script (containing CurrentLevel) is not destroyed on loading the next scene. Do this by calling GameObject.DontDestroyOnLoad(gameObject) in its void Start(). Alternatively you can make CurrentLevel a static member.
This is necessary so the value of CurrentLevel is not lost when loading the next scene. This would explain why you kept loading the same level over and over.

*In your second example, in LevelPassTest() you check if Application.loadedLevel > 4, this of course has to be Application.loadedLevel < 4. If you fix this, the second example should work just fine, too.
And yes, you are partially working on obsolete API, but that does not explain why it is not working.

A: using UnityEngine.SceneManagement;
and then use SceneManager.LoadScene() the same way we used to use Application.LoadLevel(), in unity 5.x.x Application.LoadLevel is obsolete - meaning it will be removed in the future and should not be used, and it is not guaranteed that it will work properly.
I recommend you read Unity's documentation on Scene and SceneManager classes so you can get familiar with the changes unity 5 introduced.


text:
Q: scala convert String to generic type I am am parsing a json. I would like to convert it's values to other types .
i.e
//json = JSON String
val seq = net.liftweb.json.parse(json).\\("seq").values.toString.toLong
val userName = net.liftweb.json.parse(json).\\("name").values.toString
val intNum = net.liftweb.json.parse(json).\\("intId").values.toInt

I would like to cast it using generic method more "scala" way, I tried something like this:
object Converter{
  def JSONCaster[T](json:String,s:String):T={
    net.liftweb.json.parse(json).\\(s).values.toString.asInstanceOf[T]
  }
}

but got casting error :

java.lang.ClassCastException: java.lang.String cannot be cast to
  java.lang.Long    at scala.runtime.BoxesRunTime.unboxToLong(Unknown
  Source)

A: I had the same problem and remembered that Play framework had some functionality that did something similar. After digging through the source I found this Class.
Basically, we can do something like this:
object JSONCaster {

  def fromJson[T](json: String, s: String)(implicit converter: Converter[T]): T = {
    converter.convert(net.liftweb.json.parse(json).\\(s).values.toString)
  }

  trait Converter[T] { self =>
    def convert(v: String): T
  }

  object Converter{
    implicit val longLoader: Converter[Long] = new Converter[Long] {
      def convert(v: String): Long = v.toLong
    }

    implicit val stringLoader: Converter[String] = new Converter[String] {
      def convert(v: String): String = v
    }

    implicit val intLoader: Converter[Int] = new Converter[Int] {
      def convert(v: String): Long = v.toInt
    }

    // Add any other types you want to convert to, even custom types!
  }
}

Can be called like:
JSONCaster.fromJson[Long](json, "seq")

The downside is we have to define implicit converters for all the types we want to cast to. The upside being this keeps the interface really clean and reusable.

A: Take a look at marshalling/unmarshalling as implemented in Spray. You may not need to reinvent the solution, and if you do, you can take a look at their source to see how they've implemented it.
Spray's marshalling/unmarshalling is similar to object graph serialization and works with more than just JSON so there's some additional inherent complexity within the implementation.
You could also get around manually parsing JSON and try lift-json.
lift-json is closer to JSON though through extract it can operate similar to Spray's marshaller/unmarshaller.

A: The best and nice solution I found is at Derek Wyatt's Blog -heres one of the reasons why monads are awesome

A: Here I have a generic method in scala, working with liftweb / lift-json.
As an idea, you need to provide the implicit Manifest.
import net.liftweb

private def jsonToObjectsSeq[T](jsonAsString: String)(implicit man: Manifest[T]): Seq[T] = {
  parse(jsonAsString)
    .children
    .map(_.extract[T])
}


text:
Q: CFLAGS is not taken into account, why? I'm compiling Apache 2.2.17 for my Mac OS X 10.5.8 Intel 64bit computer and I prefer the 64bit compilation so I give the necessary flags before the ./configure like so:
CFLAGS="-arch x86_64"
but the newly compiled binary just isn't 64bit:
file /usr/local/apache/bin/httpd
/usr/local/apache/bin/httpd: Mach-O executable i386
I'm confused.
I've tried variations such as:
CFLAGS="-arch x86_64"
CXXFLAGS="-arch x86_64"
LDFLAGS="-arch x86_64"
all with or without "export" or the "env" command at the start (e.g. export CFLAGS="-arch x86_64") and the result's unchanged.
What could be wrong?


text:
Q: Ajv: validate json with dynamic keys I use ajv to validate JSON data model before inserting/updating my database.
Today I want to use this structure:
const dataStructure = {
    xxx1234: { mobile: "ios" },
    yyy89B: { mobile: "android" }
};

My keys are dynamic because they are ids.
Do you know how to validate it with ajv ?
PS: as an alternative solution, i can of course use this structure:
const dataStructure = {
    mobiles: [{
        id: xxx1234,
        mobile: "ios"
    }, {
        id: yyy89B,
        mobile: "android"
    }]
};

Then I would have to loop on the array to find the ids I want.
All my queries will become more complex, it bothers me.
Thank you for your help !

A:
Below example may help you.

1.Validate dynamic key value

Update regex with your requirement.

const dataStructure = {
    11: { mobile: "android" },
    86: { mobile: "android" }
};
var schema2 = {
     "type": "object",
     "patternProperties": {
    "^[0-9]{2,6}$": { //allow key only `integer` and length between 2 to 6
        "type": "object"
        }
     },
     "additionalProperties": false
};

var validate = ajv.compile(schema2);

console.log(validate(dataStructure)); // true
console.log(dataStructure);

2.Validate array of JSON with simple data types.
var schema = {
  "properties": {
    "mobiles": {
      "type": "array", "items": {
        "type": "object", "properties": {
          "id": { "type": "string" },
          "mobile": { "type": "string" }
        }
      }
    }
  }
};
const data = {
  mobiles: [{
    id: 'xxx1234',
    mobile: "ios"
  }]
};

var validate = ajv.compile(schema);

console.log(validate(data)); // true
console.log(data);

You can add your validation as per requirement.


text:
Q: Different numeric scale labels for ggplot2 I need to present data to a non-technical audience and wanted to try a scale that uses abbreviated text with a mix of numbers. I'm fairly certain that this can be accomplished with scales package and ggplot, but I'm stuck on how to implement this.
For instance, I'd like a scale that reads '1,000,000' to say something link '1 mil' and '150,000' to say '150k' for the labels. Is there a way to accomplish this in ggplot2?
This code reproduces the plot idea and implements the comma format from the scales package.
library(tidyverse)
library(scales)
df <- tibble(x = LETTERS[1:10]) %>%
  mutate(y = seq(1e3, 1e6,
                 length.out = nrow(.)))

ggplot(df, aes(x, y))+
  geom_col()+
  scale_y_continuous(n.breaks = 10,
                     labels = dollar)

This has been asked/answer on SO. Please see Formatting large currency or dollar values to millions/billions


text:
Q: Remove SwiftUI Form padding When you use a SwiftUI Form it creates padding on the leading edge, which is fine for Form input but I would like to add additional content to the Form e.g. an image that takes the entire width of the screen, but because the image is in the Form, padding gets applied and the image gets pushed off screen slightly. How can I remove all Form padding?
struct MyForm: View {
  var body: some View {
    Form {
      Image(uiImage: someImage)
        .resizable()
        .aspectRatio(contentMode: .fill)
        .frame(width: UIScreen.main.bounds.width)

      TextField("Name", text: $name)

      // Other fields
    }
  }
}

I know that the underlying view for Form is a UITableView where I can do things like UITableView.appearance().backgroundColor = .clear to change the Form appearance, but I can't figure out how to remove the leading padding.
I also know I can move the Image view outside the Form and put everything in a stack, but that creates other issues with scrolling that I'd like to avoid.

A: Here is a solution. Tested with Xcode 11.4 / iOS 13.4
  Image(uiImage: someImage)
    .resizable()
    .aspectRatio(contentMode: .fill)
    .listRowInsets(EdgeInsets())        // << this one !!

Note: hardcode to UIScreen.main.bounds.width is not needed


text:
Q: $P(s)=1-\sqrt{\frac{2}{\zeta(s)}-\sqrt{\frac{2}{\zeta(2s)}-\sqrt{\frac{2}{\zeta(4s)}-\sqrt{\frac{2}{\zeta(8s)}-...}}}}$ Vassilev-Missana - A note on prime zeta function and Riemann zeta function¹ claims the following remarkable identity:
$$
P(s)=1-\sqrt{\frac{2}{\zeta(s)}-\sqrt{\frac{2}{\zeta(2s)}-\sqrt{\frac{2}{\zeta(4s)}-\sqrt{\frac{2}{\zeta(8s)}-...}}}},
$$
for integer $s>1$, where $\zeta(s)$ is the Riemann zeta function defined as $\sum_{n=1}^\infty \frac{1}{n^s}$ and $P(s)$ denotes the prime zeta function $\sum_{p\in\mathbb{P}}^\infty \frac{1}{p^s}$, and $\mathbb{P}$ is the set of prime numbers.
I am not a number theoretician, but the paper looks like it might contain some errors. I have already raised the question here, and it looks like I may be right. However, after performing some calculations using Wolfram Alpha, it looks like the identity might have some truth to it.
If we denote by $\epsilon(s)$ the error term $P(s)-\left(1-\sqrt{\frac{2}{\zeta(s)}-\sqrt{\frac{2}{\zeta(2s)}-...}}\right)$, we get the following results for successive finite approximations to the nested radical, in which the $k^{\rm th}$ approximation is $\sqrt{\frac{2}{\zeta(s)}-\sqrt{\frac{2}{\zeta(2s)}-\sqrt{...-\sqrt{\frac{2}{\zeta(2^{k-1}s)}}}}}$, and in this case by taking $s=2$:
\begin{array}{|c|c|}
\hline
k & \epsilon(2)\\ \hline
3 &  0.19732\ldots \\ \hline
4 &  -0.13198\ldots \\ \hline
6 &  0.04839\ldots \\ \hline
5 &  -0.035665\ldots \\ \hline
7 &  0.007512\ldots \\ \hline
8 & -0.013753\ldots \\ \hline
9 & -0.00304\ldots \\ \hline
\end{array}
so indeed it looks like $\epsilon(2)$ is converging to $0$ (note the expression "looks like", as I have not run any calculations for really large $k$).
Additionally, by taking $s=3$ the identity above would remarkably imply that:
$$
\zeta(3) = 2\left((1-P(3))^2+\sqrt{\frac{2}{\zeta(6)}-\sqrt{\frac{2}{\zeta(12)}-\sqrt{\frac{2}{\zeta(24)}-...}}}\right)^{-1},
$$
and indeed taking the finite nested radical approximation for $k=9$, the error term is already $\epsilon=-0.002516\ldots$ and seems to approach $0$ as $k\to\infty$ (note again the expression "seems to").
Is it possible that the identity still holds, nonwithstanding the issues in the paper, and if so, how may one prove it? Or do the approximations for  large $k$ actually not produce $\epsilon\to0$? If so, how can the apparent convergence be explained?

¹ Note that the journal in question is a reputed one, with Paul Erdős being at some point the editor (between '95 and '96), not a second-rate journal.

A: This has been answered in the comments by Lucia. The identity $$P(s)=1-\sqrt{\frac{2}{\zeta(s)}-\sqrt{\frac{2}{\zeta(2s)}-\sqrt{\frac{2}{\zeta(4s)}-\sqrt{\frac{2}{\zeta(8s)}-\cdots}}}}$$ is false. By subtracting $1$ from both sides and squaring, we have that $$(1-P(s))^{2}+1-\frac{2}{\zeta(s)}=1-\sqrt{\frac{2}{\zeta(2s)}-\sqrt{\frac{2}{\zeta(4s)}-\sqrt{\frac{2}{\zeta(8s)}-\cdots}}},$$ which by the identity implies that $$(1-P(s))^{2}+1-\frac{2}{\zeta(s)}=P(2s).$$ This equation, which appears as theorem $1$ in the paper, is not true.

A: This so-called "functional equation"
$$(1-P(s))^{2}+1-\frac{2}{\zeta(s)}=P(2s)$$
which was published in a 2016 paper has been used in a 2019 paper claiming to prove the generalized Riemann hypothesis. As all here have pointed out, that equation is false. A disproof has been recently published in 2021 and can be found here.  It interested me to discover this, because in 2015 I had derived this same false equation. You can find my posts about it here and here. I wanted to take it upon myself to show a generalization that highlights the error.
There is a formula that relates the partial euler prouct to the partial prime zeta function.
$$\prod_{k=1}^n\left(1-\frac{1}{{p_k}^s}\right)=\sum_{r=1}^n\sum_{\{r\}}\prod_{j=1}^l\frac{(-1)^{i_j}}{i_j!}\left(\frac{{P_n(s\cdot r_j)}}{r_j}\right)^{i_j}$$
where the sum is over partitions of $r$ and $P_n(s)=\sum_{k=1}^n\frac{1}{{p_k}^s}$, the partial prime zeta function. $p_*\in\text{Primes}$ (Note: this formula holds if we use any set of real numbers, not just the primes). For more details see Grunberg's paper On asymptotics, Stirling numbers, Gamma function, and polylogs
An equivalent representation is
$$
\prod_{k=1}^n\left(1-\frac{1}{{p_k}^s}\right)=\sum_{k=0}^n{\frac{B_k(-0!P_n(s),-1!P_n(2s),\dots,-(k-1)!P_n(ks))}{k!}}
$$
where $B_n(x_1,\dots,x_n)$ is the complete exponential Bell polynomial.
On a separate note, this also is equal to the analytic form, $\exp{\left(-\sum_{k=1}^\infty{\frac{P_n(ks)}
{k}}\right)}$
This means we can write
$$
\begin{align}
\left(1-\frac{1}{2^{s}}\right)
&=1-P_1\left(s\right)
\\
&=\color{red}{1-P_1\left(s\right)}\underbrace{\color{red}{-\frac{P_1\left(2s\right)}{2}+\frac{P_1\left(s\right)^{2}}{2}}}_0
\\
&=1-P_1\left(s\right)\underbrace{-\frac{P_1\left(2s\right)}{2}+\frac{P_1\left(s\right)^{2}}{2}}_0\space\underbrace{-\space\frac{P_1\left(3s\right)}{3}+\frac{P_1\left(2s\right)P_1\left(s\right)}{2}-\frac{P_1\left(s\right)^{3}}{6}}_0
\\
&=\cdots
\\
\left(1-\frac{1}{2^{s}}\right)\left(1-\frac{1}{3^{s}}\right)
&=\color{red}{1-P_2\left(s\right)-\frac{P_2\left(2s\right)}{2}+\frac{P_2\left(s\right)^{2}}{2}}
\\
&=1-P_2\left(s\right)-\frac{P_2\left(2s\right)}{2}+\frac{P_2\left(s\right)^{2}}{2}\underbrace{-\frac{P_2\left(3s\right)}{3}+\frac{P_2\left(2s\right)P_2\left(s\right)}{2}-\frac{P_2\left(s\right)^{3}}{6}}_0
\\
&=\cdots
\\
\left(1-\frac{1}{2^{s}}\right)\left(1-\frac{1}{3^{s}}\right)\left(1-\frac{1}{5^{s}}\right)
&=1-P_3\left(s\right)-\frac{P_3\left(2s\right)}{2}+\frac{P_3\left(s\right)^{2}}{2}-\frac{P_3\left(3s\right)}{3}+\frac{P_3\left(2s\right)P_3\left(s\right)}{2}-\frac{P_3\left(s\right)^{3}}{6}
\\
&=\cdots
\end{align}
$$
and so on.
In my case, I derived those lines with the red RHS in a different way and falsely assumed that the number of terms in the product on the LHS, as well as the number of summands in the partial prime zeta functions on the RHS could be continued beyond two terms. This is where the Riemann zeta function and the so-called "functional equation" came from.
These equations are true for any set of real numbers not just powers of primes starting from $2$. That's why as Lucia notes that the 2016 "identity" is true only if the Riemann zeta (as an Euler product) and the prime zeta functions involve a single prime term or two prime terms.
Thus a true generalized identity analogous to the false one is
$$\left(1-\frac{1}{a}\right)\left(1-\frac{1}{b}\right)=1-\left(\frac{1}{a}+\frac{1}{b}\right)-\frac{\left(\frac{1}{a^2}+\frac{1}{b^2}\right)}{2}+\frac{\left(\frac{1}{a}+\frac{1}{b}\right)^{2}}{2}$$
from which we can derive the nested radical identity
$$1-\frac{1}{a}-\frac{1}{b}=\\
\lim\limits_{n\to\infty}\sqrt{2\left(1-\frac{1}{a}\right)\left(1-\frac{1}{b}\right)-\sqrt{2\left(1-\frac{1}{a^{2}}\right)\left(1-\frac{1}{b^{2}}\right)-\cdots-\sqrt{2\left(1-\frac{1}{a^{2^n}}\right)\left(1-\frac{1}{b^{2^n}}\right)-1}}}$$


text:
Q: How to set the selected item for a  when the type is an Object? I have a class named Session defined as follows:
class Session {
  constructor(
    public id: string,
    public title: string
  ) {}
}

I created some instances of the class and exported them:
export const LocalSession = new Session("local", "Local Session");
export const RemoteSession = new Session("remote", "Remote Session");

I also created a list of the instances and exported it:
export const Sessions = [
  LocalSession,
  RemoteSession
];

I have a component that uses the list and allows the user to select a session:
import { RemoteSession, Sessions } from './session';

@Component({
  selector: 'app-device',
  templateUrl: './device.component.html',
  styleUrls: ['./device.component.css']
})
export class DeviceComponent {
  session = RemoteSession;
  sessions = Sessions;
}

A <select> is used to choose the session:
<select [(ngModel)]="session">
  <option *ngFor="let s of sessions" [value]="s">{{ s.title }}</option>
</select>

However, upon loading the page in a browser, I find that LocalSession is always selected by default instead of RemoteSession. Using Chrome's Inspector reveals that every <option> has a value of [object Object].
If I change the value attribute to:
[value]="s.id"

...then no item is selected by default. I would have to also change Sessions so that it contained a list of IDs instead of instances. I would like Sessions to remain a list of instances if at all possible. How can I set the default selection while still using instances everywhere?


text:
Q: MYSQL Error while doing partition on string column | Error Code: 1503 A PRIMARY KEY must include all columns in the table's partitioning function I've a product table with huge amount of data. I've already done indexing but still taking longer than expected while searching for data. Now I want to partition my table based on category column which contains string. I've total of 168 type of category in my table.
This is my query to achieve partition:
ALTER TABLE products  PARTITION BY LIST COLUMNS  (category) (
PARTITION category1 VALUES IN ('Battery Trays') ,
PARTITION category2 VALUES IN ('Auto Glass') ,
PARTITION category3 VALUES IN ('Bumpers AND Parts')
);

But it returns an error:
Error Code: 1503
A PRIMARY KEY must include all columns in the table's partitioning function

Here is my table structure
https://ibb.co/4jY9Tcv
Does anyone know proper method of partitioning ? why should I include PK for all columns in the table like the error says?

A: Partitioning does not inherently provide performance.  Without seeing your SELECT, it is hard to give you a straight answer.  We can discuss whether an improvement (such as 'composite') will improve performance.  So, let's see the indexes, too.
When adding (or removing) partitioning, one must redesign all the INDEXes, since the partitioning, itself, provides (sort of) a second dimension of indexing.
See this for discussing of the 4 use cases for partitioning:  http://mysql.rjweb.org/doc.php/partitionmaint
The tutorials probably tell you what can be done, but not whether partitioning is worth doing.


text:
Q: What breaking change caused my TS types to break in TS 4.7 and above (worked in v4.6) In the codebase I am working with, I wanted to upgrade TS to the latest v4.8 version from v4.6.
For some reason I get a type error of a type that used to work properly in v4.6:
Parameter 'newVal' implicitly has an 'any' type.

This parameter should actually be strictly typed and not result in type any.
I'm not sure what changed in v4.7+ that the types don't work anymore.
Here are the types we are using:
TS 4.7
TS 4.6
Edit: After simplifying the example I don't get an error, but still in v4.7+ a type which was first properly inferred is now type unknown. See the TEST const.
In v4.6 newVal1 is inferred as type number and newVal2 as type string. In v4.7+ both are type unknown.
I already simplified the TS as much as I could, the original types are even more complex

A: I identified the culprit causing the types to break. I have no clue why exactly, but everything seems to work now.
The issue was caused by the following types:
[P in TName as P]:

which does not work anymore in v4.7 and needs to be
[P in TName]:

(I had it like this, because I used to exclude a type like this: [P in TName as P extends UnacceptedPaths ? never : P]:)
I submitted an issue on GitHub for this


text:
Q: Assembly 8086. Read from the standard input several numbers, in base 2. Print on the screen these numbers in base 10 So, i have to convert the numbers from base two in base 10, and i have no idea how to do it.This is how my program looks for now, but I am not sure if what I got until now works properly. The conversion part is really giving me a hard time, but for sure I have lots of mistakes in my code, so any help would be greatly appreciated.
   assume cs:code, ds:data

data segment
msg db 'Give numbers:$'
numbers LABEL BYTE
    max_size DB 100
    numbers_len DB ?
    number DB 100 dup (?)
ten db 10
errm db 'Numbers not in binary.$'
data ends
code segment
start:

mov ax,data
mov ds,ax

mov ah,09h
mov dx,offset msg
int 21h

mov AH,0Ah
mov DX,offset numbers
int 21h

mov CL,numbers_len
mov CH,0
mov SI,0
repeat:
    mov AL,number[SI]
    cmp AL,' '
    je conversion

    check:
    cmp AL,'0'
    jb erro
    cmp AL,'1'
    ja erro

    jmp conversion
    continue:
    inc SI
    dec cx
    jcxz print
    jmp repeat

conversion:

    jmp continue

print:
    pop dx
    add dl,'0'
    mov ah,02h
    int 21h
    loop print
erro:
    mov ah,09h
    mov dx,offset errm
    int 21h

mov ax,4c00h
int 21h

code ends
end start

A: First of all, it is not possible to perform base-2 to base-10 conversion directly : you have to convert the base-2 representation into an actual value in a register, and then turn that into base-10. This is because those bases are not related to each other, e.g. there is no way to obtain 10 by applying an integer power to 2.
Here's the code for the conversion from a base-2 string to a number. No error checking is performed, every character that's not 1 is simply treated as 0.
; input : bx - the starting address of the string, cx - its length
; output : ax - contents of the string interpreted as base-2
from_bin:
  mov di, bx
  add di, cx
  sub di, 1
  xor ax, ax
  mov dx, 1

.loop:
  cmp di, bx
  jb .end

  cmp byte [di], '1'
  jne .loop_next

  add ax, dx

.loop_next:
  shl dx, 1
  sub di, 1
  jmp .loop

.end:
  ret

As you can see, the code builds up the return value in ax by adding dx to it if there is a 1 at the current position. dx corresponds to the value of 2^n in every iteration of the loop, where n is the current position in the string, starting from zero.
The code to convert a value to base-10 uses division to convert the "native" base-2 value stored in a register into consecutive base-10 digits of that value.
; input : ax - the number to convert
; di - the last writable address of the output buffer
; output : di - the address of the last written character
; destroys bx, cx, dx
to_dec:
  mov cx, 10

.loop:
  xor dx, dx
  div cx

  mov bx, dx
  or bl, '0'
  mov [di], bl
  test ax, ax
  jz .end

  sub di, 1
  jmp to_dec

.end:
  ret

The conversion is done "backwards" : it starts from the lowest position and works its way up as long as the result of the division is nonzero - this means that there is still more to convert. This is also why the function needs to obtain the last writable address of the buffer instead of its beginning.


text:
Q: AWS CloudFront signed cookies returning MalformedSignature I am trying to protect my Single Page App (SPA) behind CloudFront signed cookies. I have it setting the cookies in the browser, however whenever I try and access the page it says MalformedSignature (I'll also attach a picture at the bottom). I know my Public Key and Private Key are correct, because I can generate signed URL's with no problem. Here is my code for generating the cookies:
const cloudFront = new AWS.CloudFront.Signer('KEY_ID_HERE', PRIVATE_KEY);

const expTime = Math.floor((new Date()).getTime() / 1000) + (60 * 60 * 1);

const policy = JSON.stringify({
    "Statement": [
        {
            "Resource": "https://app.domain.click/*",
            "Condition": {
                "DateLessThan": {
                    "AWS:EpochTime": expTime// Current Time in UTC + time in seconds, (60 * 60 * 1 = 1 hour)
                }
            }
        }
    ]
});

const cookie = cloudFront.getSignedCookie({
    policy: policy
});

Another weird thing is that, if I try and load my index.html page by setting query params Policy, Signature, and Key-Pair-Id using the cookie values I get, I can see that my index page is loading correctly, but it is not able to load the scripts included in that file.
https://app.domain.click/index.html?Policy=policy_here&Signature=Signature_here&Key-Pair-Id=key_pair_id_here (This is loads the index.html file only).
I'll also attach pictures of the Behavior in my distribution.

A: So this is embarrassing... I had a new line character in the cookie and the reason I didn't catch it earlier was because it looked like the text editor I was using was moving the text to the next line. In fact, it was not and as soon as I removed the new line it started working.


text:
Q: Deploying Mobile web app on Google Cloud Hello fellow Developers,
We are developing a mobile web application using AngularJs, NodeJs and MYSQL. Our client wants to deploy the application on Google Cloud. My question is:

*

*Is deploying application which is based on above technology stack (AngularJs, NodeJs and MySQL) possible on Google Cloud?

*Can we use Mysql on Google Cloud or we have to use Google Cloud SQL to store    and retrieve data?

*Can you share your experience of deploying application on Google Cloud.

Regards,
Vikram

A: 1) You can definitely deploy any stack to Google Cloud using the Google Compute Engine.
2) Yes, you can manage your own MySQL instance on a Google Compute Engine instance. Cloud SQL has a lot of restrictions, so I wouldn't use for anything non-trivial.
3) From my experience, Google Cloud is not very mature, and hard to use unless you are playing by their rules. We were on Google Cloud for a while, but recently migrated everything to AWS due to many Google-specific issues. Support is minimal, and backlog issues are rarely addressed.


text:
Q: My 3954abg wifi card wont connect I recently installed Ubuntu 13.10 on my Lenovo 3000 n100 laptop. Running lspci in a terminal program, I discovered my wifi card is an Intel Pro/Wireless 3954abg.  The wifi card has been recognized, but will not connect.  Any help would be appreciated.

A: First, check the settings in the router. WPA2-AES is preferred; not any WPA and WPA2 mixed mode and certainly not TKIP. Second, if your router is capable of N speeds, I have better luck with a channel width of 20 MHz in the 2.4 GHz band instead of automatic 20/40 MHz. I also have better luck with a fixed channel, either 1 or 11, rather than automatic channel selection. After making these changes, reboot the router.
Next, I recommend that your regulatory domain be set explicitly. Check yours:
sudo iw reg get

If you get 00, that is a one-size-maybe-fits-all setting. Find yours here: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 Set it permanently:
gksudo gedit /etc/rc.local

Right above the line exit 0, add the line:
iw reg set IS

Of course, substitute your country code if not Iceland. Proofread carefully, save and close gedit.


text:
Q: How to set FreeSwitch and STUN/TURN when using resiprocate? I m going to build webrtc android client with my kamilio/freeswitch.
I m using resiprocate for p2p connection between clients.
How can I set freeswitch and TURN server when using resiprocate ?

A: The turn server is independent of the sip server. You don't have to setup anything about TURN on freeswitch. You just have to set your turn server address for your webrtc client.


text:
Q: Possible to create ZIM file of whole Wiki? (my own, based on mediawiki) I want to generate an offline ZIM version of our own Wiki (that runs on Mediawiki).The Collection extension is a breeze to install, but only works for selecting single pages, which in a next step can be combined into a single ZIM file.
But with a wiki of hundreds of pages this is too hard to do, based on single pages. I want to have a zim-dump of the whole wiki. I know it's possible, because there is also a zimfile for the complete wikipedia.
However, I can't find how this is done.
Anyone able to help?
Thanks in advance!

A: I don't know up to what extent this answer is still relevant, but here it goes…
After much trouble, I finally managed to create a ZIM file out of my private MediaWiki-based wiki:

*

*I started with this page: OpenZIM - Build your ZIM file

*I tested all of the listed possibilities but only mwoffliner worked (for me)

*The installation was done in a VirtualBox (version 6.0.0) Ubuntu 18.10 Desktop guest, hosted on a Mac (macOS Mojave, vs. 10.14.2)

*

*Note that I ended up using the Guest OS as headless, so the graphical interface became useless, next step will be to use a server version of Ubuntu

*After much struggle, I managed to make mwoffliner work but not without the precious help of the developers on GitHub
Please find here below step-by-step instructions on what I did. Note that the main instructions come from mwoffliner branch of openZIM on GitHub, therefore most of the credit of these instructions goes to them.
NodeJS
$ sudo apt install curl
$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash && source ~/.bashrc && nvm install stable && node --version

Image Processing & Redis & git & meson & gcc & g++ & pkg-config installation
$ sudo apt install jpegoptim advancecomp gifsicle pngquant imagemagick redis-server git meson g++ pkg-config libzim-dev

libzim-dev: manual upgrade from version 2.0.0 to version >=4.0.0

*

*(Ubuntu: uninstall packages source)

*(libzim installation instructions source)

1- If libzim 2.0.0 (libzim-dev) is already installed, then proceed with uninstalling it, else continue with point 2.
$ sudo apt remove libzim-dev #removes libzim 2.0.0
$ sudo apt purge libzim-dev
$ sudo apt autoremove #removes libzim2

2- Install libzim version >=4.0.0
$ sudo apt install cython3 liblzma-dev libgumbo-dev libicu-dev libmagic-dev libxapian-dev python-dev python-pip python-virtualenv zlib1g-dev
$ git clone https://github.com/openzim/libzim.git
$ cd libzim
$ meson . build
$ ninja -C build
$ sudo ninja -C build install
$ sudo ldconfig

ZimWriterFS Manual installation
(Source)
$ cd ~/Downloads/
$ sudo apt install librsvg2-bin
$ git clone https://github.com/openzim/zimwriterfs.git
$ cd zimwriterfs
$ meson . build
$ ninja -C build
$ sudo ninja -C build install
$ zimwriterfs
zimwriterfs usage page should appear

VirtualBox - Access VirtualBox Guest from host OS

*

*(Source)

*

*Start VirtualBox 6.x.x

*Menu File

*Choose Host Network Manager…

*Choose tab DHCP Server

*Click Create (upper left corner of the window)

*Select Enable Server

*Server Address: 192.168.56.2

*Server Mask 255.255.255.0

*Lower Address Bound: 192.168.56.3

*Upper Address Bound: 192.168.56.254

*Choose tab Adapter

*Verify that "Configure Adapter Manually" is selected and,

*IPv4 Address: 192.168.56.1

*IPv4 Network Mask: 255.255.255.0

*Click Close

*Right-click on the guest machine

*Select Settings… (or just press cmd-s)

*Choose tab Network

*Select tab Adapter 2

*Click Enable Network Adapter

*Attached to: select Host-only Adapter

*Name: vboxnet0

*Click OK

*Start Guest machine

mwoffliner command issued
This command assumes that:

*

*The MediaWiki wiki is up and running,

*VirtualBox attributed the IP address 192.168.56.5 to the guest OS (see instructions under section VirtualBox - Access VirtualBox Guest from host OS above) (check the IP address of the OS with ifconfig)

*LocalSettings.php's $wgServer = "http://192.168.56.5"; (check the IP address of the OS with ifconfig)

*The name of your wiki is YourWiki

*The MediaWiki folder containing your wiki is in /var/www/html/ (i.e., /var/www/html/YourWiki)

The actual command:
mwoffliner --mwUrl=http://192.168.56.5/YourWiki --adminEmail=foo@bar.net --verbose --redis=redis://127.0.0.1:6379 --mwWikiPath=/ --mwApiPath=api.php --localParsoid

A: Yes you can, but it's not easy. Kiwix devs are now working on a Parsoid-based solution: http://sourceforge.net/p/kiwix/other/ci/master/tree/mwoffliner/
Parsoid is, in short, the backend of the MediaWiki VisualEditor, which handles the translation of wikitext to HTML and vice versa. It has a cache of HTML versions that can be exploited for such stuff. https://www.mediawiki.org/wiki/Parsoid should give some info on how to set it up...

A: There are a few tools you may want to test. Some have been removed, but most of them are in development.

Here are some notes on how to prepare your materials and use
  zimwriterfs. The notes are incomplete as they're based on my limited
  experience using the tool (Taken from http://www.openzim.org/wiki/Build_your_ZIM_file)

Here is the link to create a ZIM file from existing HTML contents
"See http://www.openzim.org/wiki/Zimwriterfs_instructions for an overview and read the section below on zimwriterfs for some additional context"
I have tried another windows program called Zim - A Desktop Wiki http://zim-wiki.org/ is limited, but you can give it a try. It does the opposite, converts ZIMs to HTML.
Anyway, let us know how it went, Im also interested on building my own zim files. Good luck.


text:
Q: WinAPI Named Pipe location HANDLE pipe = CreateFile( L"\\\\.\\pipe\\my_pipe",
                              GENERIC_READ, // only need read access
                              FILE_SHARE_READ | FILE_SHARE_WRITE,
                              NULL,
                              OPEN_EXISTING,
                              FILE_ATTRIBUTE_NORMAL,
                              NULL );

I'm new to win api and i'd like to know where is the "my_pipe" file created on the hard disk?
I can't find it anywhere near the binary or sources

A: Windows doesn't follow the UNIX philosophy "everything is a file", so the named objects you create with the kernel APIs aren't files, but are objects in various NT objects namespaces. You can see them with tools like WinObj.
You may want to have a look at the article about the object manager in Windows.


text:
Q: JS timeout not firing Just can't seem to figure this out, how to prevent the outer loop continuing until the inner loop has executed using setTimeout:
    function $(s) { return document.getElementById(s); }
    var i = 0;
    for (i=0; i<6; i++){
        $('t'+i).className = 'show';
        cl('t'+i);
        for (var j=0; j<50; j++){
            cl('b'+i+'='+j+'%');
            setTimeout(function(){ $('b'+i).style.width = j+'%';},200);
        }
    }

This little bit of code is supposed to first make elements t0 visible, and then set the width of another element b0 in 1% steps with a time interval of 200ms, and then continue with t1,b1, t2,b2 etc etc.
But there's no 200ms delay, the whole code executes immediately.
--- EDIT ---
I have not explained very well, here's what I want to do:
1. show element Ax
2. increase element Bx width by 1% every 200ms until 50%
3. wait until element Bx reaches 50% before continuing
4. increment x
5. goto 1

A: Two problems:

*

*The timeout functions see the wrong i and j values

*They all run at the same time (200ms later)

The timeout functions see the wrong i and j values
The main problem is that the function you're passing into setTimeout has an enduring reference to the i and j variables, not copies of them as of when the function was created. That means all of the functions will see the value of i and j as of when they run, which will be 6 and 50 respectively. This is called "closing over" those variables (and the function is called a "closure").
The usual way to fix this is to create the functions in a way that they close over something that doesn't change. There are a couple of ways to do that; my favorite is to use a factory function:
function $(s) { return document.getElementById(s); }
var i = 0;
for (i=0; i<6; i++){
    $('t'+i).className = 'show';
    cl('t'+i);
    for (var j=0; j<50; j++){
        cl('b'+i+'='+j+'%');
        setTimeout(makeHandler(i, j), 200);
    }
}
function makeHandler(ivalue, jvalue) {
    return function(){ $('b'+ivalue).style.width = jvalue+'%';};
}

Now we call makeHandler, and it returnns us a function that closes over ivalue and jvalue, which won't change. Or a refinement of the above which lets us dispose of the maker function when we're done with it:
function $(s) { return document.getElementById(s); }
var i = 0;
var makeHandler = function(ivalue, jvalue) {
    return function(){ $('b'+ivalue).style.width = jvalue+'%';};
};
for (i=0; i<6; i++){
    $('t'+i).className = 'show';
    cl('t'+i);
    for (var j=0; j<50; j++){
        cl('b'+i+'='+j+'%');
        setTimeout(makeHandler(i, j), 200);
    }
}
makeHandler = undefined;

If you can rely on ES5 features (because of the environment you're targeting, or because you've included an ES5 shim), you can get much the same effect using the new Function#bind. Function#bind creates a new function just like makeHandler does, but there's always the possibility the engine can optimize a bit:
function $(s) { return document.getElementById(s); }
var i = 0;
for (i=0; i<6; i++){
    $('t'+i).className = 'show';
    cl('t'+i);
    for (var j=0; j<50; j++){
        cl('b'+i+'='+j+'%');
        setTimeout(handler.bind(undefined, i, j), 200);
    }
}
function handler(){
    $('b'+ivalue).style.width = jvalue+'%';
}

The first argument to bind is what this should be in the function; in our case we don't care, so I've specified undefined (which means the function will get this referencing the global object — window, on browsers — unless this is strict mode code, in which case this will actually be undefined).
They all run at the same time (200ms later)
All of your functions are being scheduled to run 200ms after the above code. And so they will. :-) If you want to space them out, you'll want to increase that 200ms for each call to setTimeout. We can just multiply by i and j:
setTimeout(makeHandler(i, j), (200 * i * j) + 200);

Now the first one will run after 200ms, the second one 200ms later, etc. The whole thing will take about a minute to complete. This assumes you want the first element to grow, then the next, then the next, as opposed to all six of them growing in parallel with each other.
Alternately, you might want to have each function call its successor. That's probably what I'd do. So rather than scheduling 300 function calls, just schedule one and when it happens, schedule the next:
function $(s) { return document.getElementById(s); }

// Our counters are here
var i = 0, j = 0;

// This handles the outer portion of the loop (mostly)
function outer() {
    $('t'+i).className = 'show';
    cl('t'+i);
    j = 0;
    // Schedule the first inner portion 200ms from now
    setTimeout(inner, 200);
}

// This handles the inner portion of the loop (mostly)
function inner() {
    // Do this bit
    $('b'+i).style.width = j+'%';
    ++j;
    if (j < 50) {
       // Continue the inner loop in 200ms
       setTimeout(inner, 200);
    }
    else {
       // Set up next outer loop
       j = 0;
       ++i;
       if (i < 6) {
           // Not done yet, keep going
           setTimeout(outer, 200);
       }
     }
}

// Kick it off
setTimeout(outer, 200);

In the above, I've also moved these lines:
$('t'+i).className = 'show';
cl('t'+i);

...into the delayed code, which I suspected was appropriate.
More to explore:

*

*Closures are not complicated

A: It's because you're not closing over the i and j:
setTimeout(function(i, j) {
    return function() {
        $('b'+i).style.width = j+'%';
    }
}(i, j), 200);

A: setTimeout(function () { alert('Refreshing…'); }, 2000);

It means after two seconds (2000 ms), show alert


text:
Q: Importing library in python (Pycharm) These are the libraries within the script asked for import
## Import libraries
import numpy
import dill
import pandas
import peakutils
import os
import scipy
from scipy.signal import butter, lfilter, freqz
import smooth

from peakutils.plot import plot
from matplotlib import pyplot

I did several however, not for butter,lfilter, freqz, os,
what I have to do?
I imported several libraries but not all.